如何使用LINQ来选择对象,最低或最高属性值 [英] How to use LINQ to select object with minimum or maximum property value

查看:388
本文介绍了如何使用LINQ来选择对象,最低或最高属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可为空DATEOFBIRTH属性Person对象。有没有一种方法使用LINQ查询人的对象列表的之一,最早/最小DATEOFBIRTH值。

这是我开始的:

  VAR firstBornDate = People.Min(P => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue));
 

空DATEOFBIRTH值,以排除他们闵考虑设置为DateTime.MaxValue(假设至少有一个指定的DOB)。

不过,所有这些都对我来说是设置firstBornDate为datetime值。我想获得的是相匹配的Person对象。我是否需要写第二个查询像这样:

  VAR长子= People.Single(P => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue)== firstBornDate);
 

还是有这样做的一个更精简的方式?

解决方案

  People.Aggregate((curMin,X)=>(curMin == NULL ||(x.DateOfBirth? ?DateTime.MaxValue)所述; curMin.DateOfBirth×:curMin))
 

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.

Here's what I started with:

var firstBornDate = People.Min(p => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue));

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

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.GetValueOrDefault(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆