我有Beam
个对象的列表。如何使用LINQ将Select
具有最大Depth
属性的属性放入另一个列表?
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};
我希望:
SelectedList = {beam1, beam3}
答案 0 :(得分:2)
使用Max
和Where
的组合:
var result = Beams.Where(b => b.Depth == Beams.Max(x => x.Depth));
但是肯定应该通过将其分成两行进行优化,这样就不会再次调用Max
:
var max = Beams.Max(x => x.Depth);
var result = Beams.Where(b => b.Depth == max);
答案 1 :(得分:1)
您可以使用GroupBy
+ OrderByDescending
:
List<Beam> maxDepthGroupList = Beams
.GroupBy(b => b.Depth)
.OrderByDescending(g => g.Key)
.First()
.ToList();
答案 2 :(得分:1)
var Beams = new List<Beam> {beam1, beam2, beam3};
var selected = Beams.GroupBy(b => b.Depth).OrderByDescending(g => g.Key).First();
修改:
首先,按Depth属性对结果进行分组。每组可以包含一个或多个结果
然后按键(本例中为Depth)降序对组进行排序
然后,您将获得具有最大深度的第一个元素。
答案 3 :(得分:1)
var maxDepth = Beams.Max( b => b.Depth );
List<Beam> SelectedList = Beams.Where( b => b.Depth == maxDepth );