假设我有
class Product
{
public int Id {get; set;}
public string Name {get; set;}
public int Order {get; set;}
}
和我的数据有,
products[0] = new Product { Id = 1, Name = "P1", Order = 1 };
products[1] = new Product { Id = 1, Name = "P2", Order = 2 };
products[2] = new Product { Id = 1, Name = null, Order = 3 };
products[3] = new Product { Id = 2, Name = "P3", Order = 4 };
products[4] = new Product { Id = 2, Name = null, Order = 5 };
products[5] = new Product { Id = 2, Name = null, Order = 6 };
我需要的是每个Product.Id的Name的最后一个非空值(按order desc排序)。所以我的最终输出是这样的,
items[0] = new { Id = 1, Name = "P2"};
items[1] = new { Id = 2, Name = "P3"};
如果Id=1
,我有3个名称(P1
, P2
, null
)和非空名称(P1
, P2
),但最后一个是P3
。
这将使最后一批产品按顺序排列。
var lastOrders = products
.Where(x => x.Name != null) // Remove inapplicable data
.OrderBy(x => x.Order) // Order by the Order
.GroupBy(x => x.Id) // Group the sorted Products
.Select(x => x.Last()); // Get the last products in the groups
var result = products
.GroupBy(p => p.Id)
.Select(g => g.OrderBy(x => x.Order).Last(x => x.Name != null));
这将给出您想要的输出:
products.GroupBy(p => p.Id)
.Select(g => g.OrderByDescending(gg => gg.Name)
.Where(gg => gg.Name != null)
.Select(gg => new { gg.Id, gg.Name })
.First());
这个任务可以使用下面的Linq语句来解决。
var Result = products.OrderBy().Where( null != iProduct.Name ).First();
这要求products
至少包含一个Name
是null
的项,否则将抛出Exception
。另外,
var Result = products.OrderBy().Where( null != iProduct.Name ).FirstOrDefault();
将返回null
,如果products
不包含此条目。
Try with:
var expectedProduct =products.Where(p => p.Id != null).OrderByDescending(p => p.Order).GroupBy(p => p.Id).Last()