HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertyobjectlinqhowwithusemaximumvalueminimumselect

Problem

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?

Solution

People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <
    curMin.DateOfBirth ? x : curMin))

Code Snippets

People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <
    curMin.DateOfBirth ? x : curMin))

Context

Stack Overflow Q#914109, score: 350

Revisions (0)

No revisions yet.