Bohn
Bohn

Reputation: 26929

Finding the minimum date value from a list of dates

This will give me a list of my Start Dates: ( they are stored as STRING )

var startDate = myValues.Select(t => t.StartDate).ToList();

I only need it to choose the earliest date value from it. And if it is an empty string then that is also the winner, if no empty string then just see which one is really earliest.

Is there a way I can use LINQ and combine this part with the part I have above to find it on one go? Instead of writing more logic separately to find the min date from that list?

Upvotes: 0

Views: 1591

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460380

Something like:

string winner = myValues.Select(t => t.StartDate)
    .Select(s => new{ str = s, date = DateTime.TryParse(s, out DateTime dt) ? dt : new DateTime?() })
    .OrderByDescending(x => String.IsNullOrEmpty(x.str))
    .ThenByDescending(x => x.date.HasValue)
    .ThenBy(x => x.date.GetValueOrDefault())
    .Select(x => x.str)
    .First();

Upvotes: 2

Hamzeh.Ebrahimi
Hamzeh.Ebrahimi

Reputation: 305

this may help you

var result = myValues?.Where(t=>!string.IsNullOrEmpty(t.StartDate))?.
  Select(t => { DateTime.TryParse(t.StartDate, out DateTime date); return date;})?.
  Min();

Upvotes: 0

Related Questions