[英]Get the objects with the maximum value for a specific property from a list using LINQ
I have a list of Beam
objects. 我有一个Beam
对象列表。 Each Beam
class has X
, Y
properties for coordinates and it also has a Height
property. 每个Beam
类都有X
, Y
属性作为坐标,并且还具有Height
属性。
Now here is my initial list: 现在这是我的初始列表:
List1 = {beam1, beam2, beam3, beam4}
beam1 = {X = 0, Y = 0, Height = 40}
beam2 = {X = 200, Y = 0, Height = 40}
beam3 = {X = 200, Y = 0, Height = 60}
beam4 = {X = 400, Y = 0, Height = 40}
As you can see beam2 and beam3 are at the same point, I want a list where I only have the beam with the maximum Height
at each distinct point. 如您所见, beam2和beam3在同一点,我想要一个列表,在该列表中,我在每个不同的点仅具有最大Height
的波束。
So the final list using LINQ
would be: 因此,使用LINQ
的最终列表为:
List2 = {beam1, beam3, beam4}
You can use GroupBy
to group them based on X
and Y
and select the item with the maximum Height from each group: 您可以使用GroupBy
根据X
和Y
对它们进行分组,然后从每个组中选择具有最大高度的项目:
beams.GroupBy(b => new { b.X, b.Y })
.Select(g => g.First(x => x.Heigth == g.Max(h => h.Height)))
.ToList();
Personally I would use MaxBy
method to get the beam with max. 我个人将使用MaxBy
方法获得最大光束。 Height: 高度:
beams.GroupBy(b => new { b.X, b.Y })
.Select(g => g.MaxBy(x => x.Heigth))
.ToList();
尝试这个:-
var query = List1.GroupBy(x => new { x.X, x.Y }).Select(x => x.First(y => y.Height == x.Max(z => z.Height)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.