使用LINQ选择具有最小或最大属性值的Object
要查找DateOfBirth
属性值最小的Person
对象,您可以利用LINQ的聚合功能。请考虑以下方法:
<code class="language-csharp">var firstBorn = People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) < (curMin.DateOfBirth ?? DateTime.MaxValue)) ? x : curMin);</code>
以下是其工作原理:
Aggregate
方法用于遍历集合并累积单个结果。
传递给Aggregate
的匿名函数采用两个参数:
curMin
:到目前为止遇到的当前最小DateOfBirth
值(如果尚未找到任何值,则为null)。x
:正在处理的当前Person
对象。条件(x.DateOfBirth ?? DateTime.MaxValue)
检查x
是否具有有效的DateOfBirth
值;如果为null,则将其设置为DateTime.MaxValue
(假设没有有效的DateOfBirth
值超过此值)。
比较(curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) < (curMin.DateOfBirth ?? DateTime.MaxValue))
确定哪个对象具有更早的出生日期。
累积过程持续进行,直到评估集合中的所有Person
对象,最终产生DateOfBirth
值最早的Person
对象。
This revised explanation clarifies the comparison logic within the Aggregate method, making the process easier to understand.
以上是如何使用LINQ找到具有最小或最大属性值的人?的详细内容。更多信息请关注PHP中文网其他相关文章!