Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LINQ to select object with minimum or maximum property value

Tags:

c#

.net

linq

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 ?? DateTime.MaxValue) == firstBornDate); 

Or is there a leaner way of doing it?

like image 703
slolife Avatar asked May 27 '09 05:05

slolife


People also ask

How do you find the minimum value in LINQ?

In LINQ, you can find the minimum element of the given sequence by using Min() function. This method provides the minimum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.

How does select work in LINQ?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.

Does LINQ select create new object?

The type of sequence returned by a query is determined by the type of value returned by the select clause. LINQ select can return a sequence that contains elements created during the execution of the query.

What are the uses of LINQ to Objects?

In a nutshell, LINQ to Objects provides the developer with the means to conduct queries against an in-memory collection of objects. The techniques used to query against such collections of objects are similar to but simpler than the approaches used to conduct queries against a relational database using SQL statements.


1 Answers

People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <     curMin.DateOfBirth ? x : curMin)) 
like image 161
Ana Betts Avatar answered Sep 26 '22 03:09

Ana Betts