用 LINQ 合并两个 IEnumerable

cog*_*el0 3 .net c# linq

我有以下课程

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

    public int Version { get; set; }

    (...)
}
Run Code Online (Sandbox Code Playgroud)

我有以下几点IEnumerable<Application>

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

IEnumerable<Application> applications2 = new List<Application>
{
    new Application {Id = 1, Version = 2},
    new Application {Id = 3, Version = 2}
    new Application {Id = 4, Version = 1}
};
Run Code Online (Sandbox Code Playgroud)

如何IEnumerable<Application>使用 LINQ将它们合并为一个,同时确保如果两个Applications相同,Id只有最高的一个Version被添加到新的IEnumerable<Application>,有效地我的最终`IEnumerable 应该相当于:

IEnumerable<Application> final = new List<Application>
{
    new Application {Id = 1, Version = 2},
    new Application {Id = 2, Version = 1},
    new Application {Id = 3, Version = 3},
    new Application {Id = 4, Version = 1}
}
Run Code Online (Sandbox Code Playgroud)

Gur*_*ron 5

您可以通过以下方式GroupBy与在组中选择最大值结合使用Aggregate

IEnumerable<Application> final = applications1
    .Concat(applications2)
    .GroupBy(a => a.Id)
    .Select(g => g.Aggregate((acc, curr) => acc.Version > curr.Version ? acc: curr))
    .ToList();
Run Code Online (Sandbox Code Playgroud)