Reputation: 5444
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
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
Reputation: 4487
var maxDepth = Beams.Max( b => b.Depth );
List<Beam> SelectedList = Beams.Where( b => b.Depth == maxDepth );
Upvotes: 1
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
Reputation: 460108
You can use GroupBy
+ OrderByDescending
:
List<Beam> maxDepthGroupList = Beams
.GroupBy(b => b.Depth)
.OrderByDescending(g => g.Key)
.First()
.ToList();
Upvotes: 1