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!
When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault() .
SingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
FirstOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the first element of a sequence, or a specified default value if the sequence contains no elements. FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.
Try
var d = lst1.Where(q => q <= DateTime.Now).DefaultIfEmpty().Max();
Your result will now contain DateTime.MinValue
if there are no matches
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With