Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine sequence contains no element using LINQ [duplicate]

Tags:

c#

.net

linq

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!

like image 544
Friend Avatar asked Aug 09 '12 13:08

Friend


People also ask

How do you know if a sequence contains no elements?

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() .

What is the difference between 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.

What is FirstOrDefault C#?

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.


1 Answers

Try

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

Your result will now contain DateTime.MinValue if there are no matches

like image 54
podiluska Avatar answered Oct 06 '22 00:10

podiluska