Alex Rivera | Logout

Determine sequence contains no element using LINQ

Asked 2012-08-09T13:08:28.003
33

Possible Duplicate:
LINQ: Max or Default?

I have some LINQ to filter DateTime vars.

List<DateTime> lst1 = new List<DateTime>();

 //.... add DataTime here

var d = lst1.Where(q => q <= DateTime.Now).Max();

And if I have no matched item the exceptions occurs.

I need to get empty d or at least null and I don't need exception here at all.

How do I can fix it?

Thank you!

Edit
Report

1 Answer

5

Max() throws an ArgumentNullException if the source doesn't have any elements. You could write an extension method that checks for this and returns a null (or whatever you want) if there aren't any elements.

public static Nullable<DateTime> MaxOrNull(this IEnumerable<DateTime> source)
{
    if (source.Count() == 0)
        return null;
    else
        return source.Max();
}
answered 2012-08-09T13:29:42.010

Your Answer