Select 每个产品的最后一个不可为 null 的项目?

Select Last non null-able item per product?

假设我有,

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 个名称(P1P2null)和不可为 null 的名称(P1P2) 但最后一个是 P3.

可以使用以下 Linq 语句解决该任务。

var Result = products.OrderBy().Where( null != iProduct.Name ).First();

这要求 products 包含至少一项 Namenull,否则将抛出 Exception。或者,

var Result = products.OrderBy().Where( null != iProduct.Name ).FirstOrDefault();

将 return null 如果 products 不包含此类项目。

试试:

var expectedProduct =products.Where(p => p.Id != null).OrderByDescending(p => p.Order).GroupBy(p => p.Id).Last()

这应该按顺序获取最后的产品。

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());