简体   繁体   English

使用LINQ从列表中获取具有特定属性最大值的对象

[英]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类都有XY属性作为坐标,并且还具有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. 如您所见, beam2beam3在同一点,我想要一个列表,在该列表中,我在每个不同的点仅具有最大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根据XY对它们进行分组,然后从每个组中选择具有最大高度的项目:

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.

相关问题 使用Linq从对象属性列表中获取最小和最大时间值 - Get minimum and maximum time value from list of object property using Linq 使用LINQ,获取包含特定属性值的对象的列表 - Using LINQ, get a list of objects that contain a particular property value Linq获取自定义对象的列表,其中字典属性中包含的某个值等于一个特定值 - Linq to get list of custom objects where a certain value contained within dictionary property equals a specific value 使用linq group by从具有DateTime属性的对象列表获取具有间隔StartDate,EndDate的列表 - Using linq group by to get from a list of objects with a DateTime property to a list with an interval StartDate, EndDate 使用LINQ从列表中获取类型的对象 - Using LINQ to get objects of type from a list 在 LINQ 中的列表中获取列表中的最大值 - Get maximum value in a list within a list in LINQ 使用 Linq 查询选择属性的任何值与列表中的值匹配的对象 - Using a Linq query to select objects where any value of a property matches values from a list 使用linq按对象的2属性排序对象列表 - sorting list of objects by 2 property of that objects using linq 使用linq获取具有特定对象属性的列表的一部分 - Using linq to get part of a list with specific object property 如何从列表中获取特定属性的值? - How to get value of specific property from list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM