【问题标题】:Select Last non null-able item per product?选择每个产品的最后一个不可为空的项目?
【发布时间】:2015-08-08 07:05:43
【问题描述】:

假设我有,

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 的最后一个(按 Order desc 排序)不可为空的 Name 值。所以我的最终输出看起来像,

items[0] =  new { Id = 1, Name = "P2"}; 
items[1] =  new { Id = 2, Name = "P3"}; 

如果 Id=1,我有 3 个名称(P1P2null)和不可为空的名称(P1P2),但最后一个是 P3

【问题讨论】:

  • last 是什么意思。你的意思是Id的最后一个吗?
  • CommuSoft,是的,每个 ID 最后一个。 BrokenGlass 我也在尝试。

标签: c# .net linq c#-5.0


【解决方案1】:

这将为您提供所需的输出:

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

【讨论】:

    【解决方案2】:
    var result = products
                  .GroupBy(p => p.Id)
                  .Select(g => g.OrderBy(x => x.Order).Last(x => x.Name != null));
    

    【讨论】:

      【解决方案3】:

      这应该按顺序排列最后的产品。

      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
      

      【讨论】:

        【解决方案4】:

        尝试:

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

        【讨论】:

        • 你的预期输出是什么?
        【解决方案5】:

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

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

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

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

        如果products 不包含此类项目,将返回null

        【讨论】:

        • 我的意思是每个 ID 看到我的预期结果
        猜你喜欢
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 2021-10-23
        • 1970-01-01
        • 2017-05-10
        相关资源
        最近更新 更多