让我说我有,
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个姓名(P1
,P2
,null
)和不可为空的姓名(P1
,P2
)但最后一个是P3
。
答案 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
至少包含Name
为null
的项目,否则将引发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()