I have a list of Foo's.
Foo has a CreateDate of type DateTime?
I want to get the oldest Foo. I tryed with the intuitive way, but I get a possible System.InvalidOperationException.
DateTime oldestFoo =
(from f in allFoos where f.CreateDate.HasValue select f.CreateDate.Value).Min();
Is there something I missed or is it just not possible this way?
I can do it without LinQ this way, but I want to learn the other approach too.
DateTime oldestFoo = DateTime.MaxValue;
foreach (var foo in allFoos)
{
if (foo.CreateDate.HasValue && oldestFoo > foo.CreateDate)
{
oldestFoo = (DateTime)foo.CreateDate;
}
}
Just in case you’re still stuck, you might want to consider using
DefaultIfEmpty– see if this helps:I don’t think you want to use
GetValueOrDefaultwithin your query, as otherwise you’ll still have a problem if the first query returns no results at all.