Rog*_*lin 1 c# linq ienumerable merge
我已经简化了我的问题
public class Application
{
public int Id { get; set; }
public int Version { get; set; }
public int Status { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的 3 个清单:
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}
};
Run Code Online (Sandbox Code Playgroud)
我想制作这个:
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}
};
Run Code Online (Sandbox Code Playgroud)
即具有最高 Version 和 Status 值的列表。我尝试过使用 LINQ 但我不明白。
我最好的是这个,但它只是获得最高版本。我不明白当有 2 个属性可供选择时我该怎么做:
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();
Run Code Online (Sandbox Code Playgroud)
您应该使用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();
Run Code Online (Sandbox Code Playgroud)