我把我的问题简化了

public class Application
{
    public int Id { get; set; }
    public int Version { get; set; }
    public int Status { get; set; }
}

我的3个 list :

IEnumerable<Application> applications1 = new List<Application>
{
    new Application {Id = 1, Version = 1, Status = 1},
    new Application {Id = 2, Version = 1, Status = 1},
    new Application {Id = 3, Version = 3, Status = 1}
};

IEnumerable<Application> applications2 = new List<Application>
{
    new Application {Id = 1, Version = 2, Status = 2},
    new Application {Id = 2, Version = 2, Status = 2},
    new Application {Id = 3, Version = 1, Status = 0}
};

IEnumerable<Application> applications3 = new List<Application>
{
    new Application {Id = 1, Version = 5, Status = 1},
    new Application {Id = 2, Version = 0, Status = 1},
    new Application {Id = 3, Version = 6, Status = 1}
};

我想制作这个:

IEnumerable<Application> applications4 = new List<Application>
{
    new Application {Id = 1, Version = 5, Status = 2},
    new Application {Id = 2, Version = 2, Status = 2},
    new Application {Id = 3, Version = 6, Status = 1}
};

即具有the highest value of Version and Status个的一个列表. 我试过用LINQ,但我不明白.

我最好的就是这个,但它只能得到最高版本.当有两个属性可供 Select 时,我不明白我该怎么办:

IEnumerable<Application> applications4 = applications1
    .Concat(applications2)
    .Concat(applications3)
    .GroupBy(a => a.Id)
    .Select(g => g.Aggregate((acc, curr) => acc.Version > curr.Version ? acc: curr ))
    .ToList();

推荐答案

您应该使用Max()从分组的属性中获取最大值.

IEnumerable<Application> applications4 = applications1
    .Concat(applications2)
    .Concat(applications3)
    .GroupBy(a => a.Id)
    .Select(g => new Application
            {
                Id = g.Key,
                Version = g.Max(x => x.Version),
                Status = g.Max(x => x.Status)
            })
    .ToList();

Csharp相关问答推荐

在实际上是List T的 IESEARCH上多次调用First()是否不好?

Microsoft. SQLServer. Types(106.1000.6)在try 从用户定义的类型检索值时引发异常

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

Entity Framework Core 8 dbcontext—无法以多对多关系添加某些行'

实体框架核心上是否支持使用NPGSQL的字符串聚合?

ITypeLib2.GetLibStatistics()在C#中总是抛出AccessViolationException

WPF DataGrid中的三维数据

创建临时Collection 最有效的方法是什么?堆栈分配和集合表达式之间的区别?

如何忽略API JSON响应中的空字符串?

如何在C#中从正则表达式中匹配一些数字但排除一些常量(也是数字)

从.Net 6 DLL注册和检索COM对象(Typelib导出:类型库未注册.(异常来自HRESULT:0x80131165))

TCPClient阅读流

反序列化私有成员

如何将MemberInitExpression添加到绑定中其他Lambda MemberInitExpression

具有以接口为其类型的属性的接口;类指定接口的实现,但无效

该函数不能检测两条曲线的交点

如何使用用于VS代码的.NET Maui扩展在我的iOS/Android设备或模拟器上进行调试?

EF Core 7-忽略模型绑定中的虚拟属性

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

无法通过服务控制台启动.NET Core 6.0服务(错误1053)