如何使用LINQ来选择对象,最低或最高属性值如何使用、属性、最低、对象

2023-09-02 10:15:09 作者:帮女生绑头发的男生最可爱

我有一个可为空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))
 
在visual studio中创建SQL Server数据库用于LinqDataSource配置数据源

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