假设我有,
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 名称的最后一个(按订单描述排序)不可为空的值。所以我的最终输出看起来像,
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
关于c# - 选择每个产品的最后一个不可为空的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30461399/