简体   繁体   中英

Select objects from a list using LINQ based on a property

I have list of Beam objects. How can I Select the ones with maximum Depth property into another list using 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 :

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:

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

You can use 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();


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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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