Vahid
Vahid

Reputation: 5444

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}

Upvotes: 1

Views: 6463

Answers (4)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

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

Upvotes: 4

bit
bit

Reputation: 4487

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

Upvotes: 1

Amir Popovich
Amir Popovich

Reputation: 29836

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.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use GroupBy + OrderByDescending:

List<Beam> maxDepthGroupList = Beams 
    .GroupBy(b => b.Depth)
    .OrderByDescending(g => g.Key)
    .First()
    .ToList();

Upvotes: 1

Related Questions