简体   繁体   English

使用LINQ基于属性从列表中选择对象

[英]Select objects from a list using LINQ based on a property

I have list of Beam objects. 我有Beam对象的列表。 How can I Select the ones with maximum Depth property into another list using LINQ? 我该如何Select与最大的那些Depth物业为使用LINQ另一个列表?

public class Beam
{
    public double Width { get; set; }
    public double Depth { get; set; }
}

var beam1 = new Beam() {Width = 40, Depth = 50};
var beam2 = new Beam() {Width = 40, Depth = 40};
var beam3 = new Beam() {Width = 30, Depth = 50};

var Beams = new List<Beam> {beam1, beam2, beam3};

I want to have: 我希望有:

SelectedList = {beam1, beam3}

Use combination of Max and Where : 使用MaxWhere组合:

var result = Beams.Where(b => b.Depth == Beams.Max(x => x.Depth));

but for sure it should be optimized by splitting it into two lines so Max won't be called again and again: 但可以肯定的是,应该将其分为两行进行优化,以免Max一次又一次地被调用:

var max = Beams.Max(x => x.Depth);
var result = Beams.Where(b => b.Depth == max);

You can use GroupBy + OrderByDescending : 您可以使用GroupBy + OrderByDescending

List<Beam> maxDepthGroupList = Beams 
    .GroupBy(b => b.Depth)
    .OrderByDescending(g => g.Key)
    .First()
    .ToList();
var Beams = new List<Beam> {beam1, beam2, beam3};

var selected = Beams.GroupBy(b => b.Depth).OrderByDescending(g => g.Key).First();

Edit: 编辑:
First you group your result by the Depth property. 首先,您将结果按“深度”属性分组。 Each group can contain one or more results. 每个组可以包含一个或多个结果。
Then you order the groups by the key(Depth in this case) descending. 然后按降序(在这种情况下为深度)对组进行排序。
And then, you take the first element which will be the group with the max depth. 然后,选择第一个元素,即最大深度的组。

var maxDepth = Beams.Max( b => b.Depth );
List<Beam> SelectedList = Beams.Where( b => b.Depth == maxDepth );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM