如何使用 LINQ 选择具有最小或最大属性值的对象 [英] How to use LINQ to select object with minimum or maximum property value
问题描述
我有一个具有 Nullable DateOfBirth 属性的 Person 对象.有没有办法使用 LINQ 查询具有最早/最小 DateOfBirth 值的 Person 对象列表?
I have a Person object with a Nullable DateOfBirth property. Is there a way to use LINQ to query a list of Person objects for the one with the earliest/smallest DateOfBirth value?
这是我的开始:
var firstBornDate = People.Min(p => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue));
Null DateOfBirth 值设置为 DateTime.MaxValue 以将它们排除在 Min 考虑之外(假设至少有一个具有指定的 DOB).
Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB).
但我所做的只是将 firstBornDate 设置为 DateTime 值.我想得到的是与之匹配的 Person 对象.我是否需要像这样编写第二个查询:
But all that does for me is to set firstBornDate to a DateTime value. What I'd like to get is the Person object that matches that. Do I need to write a second query like so:
var firstBorn = People.Single(p=> (p.DateOfBirth ?? DateTime.MaxValue) == firstBornDate);
或者有更精简的方法吗?
Or is there a leaner way of doing it?
推荐答案
People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <
curMin.DateOfBirth ? x : curMin))
这篇关于如何使用 LINQ 选择具有最小或最大属性值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!