c# - 选择每个产品的最后一个不可为空的项目?

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

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

如果 Id=1,我有 3 个名称(P1P2null)和非可为空的名称(P1P2),但最后一个是 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/

相关文章:

c# - 表达式几乎相同,但其中一个不起作用

c# - 如何获得系统权限

.net - 为什么我不能为 Sql Server Reporting Services 强制使用 SSL?

.net - 如何使用AutoMapper.ForMember?

c# - 应该更喜欢 ImmutableDictionary 还是 ImmutableSortedDictionary?

C# 使用 WHERE 获取每个第 n 个元素,结果很奇怪

c# - 完成 IQueryable 通用列表排序的更好方法?

c# - 为什么 IDictionary<TKey, TValue> 同时实现 ICollection 和 IEnumerable

java - 将 Linq 查询转换为 Java 8

C# 子类返回类型的协方差