选择每个产品的最后一个不可归零商品?

时间:2015-05-26 14:27:14

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

让我说我有,

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

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

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

5 个答案:

答案 0 :(得分:4)

这应该是最后的产品。

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

答案 1 :(得分:1)

var result = products
              .GroupBy(p => p.Id)
              .Select(g => g.OrderBy(x => x.Order).Last(x => x.Name != null));

答案 2 :(得分:1)

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

If Mobile Then
    <input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
    <input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />

答案 3 :(得分:0)

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

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

这要求products至少包含Namenull的项目,否则将引发Exception。或者,

var Result = products.OrderBy().Where( null != iProduct.Name ).FirstOrDefault();
如果null不包含此类项目,

将返回products

答案 4 :(得分:0)

尝试:

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