Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's FirstOrDefault for DateTime in Linq?

Tags:

c#

linq

If I have a query that returns a DateTime, what's the value of FirstOrDefault()? Is there a generic way to get the default value of a C# scalar? Example:

var list = (from item in db.Items 
    where item.ID==1234
    select item.StartDate).FirstOrDefault();

Edit: Assume that the column StartDate can't be null.

like image 589
Keltex Avatar asked Apr 23 '10 17:04

Keltex


People also ask

What is the use of FirstOrDefault in Linq?

Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection.

What is FirstOrDefault in Linq C#?

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource) Returns the first element of the sequence that satisfies a condition, or a specified default value if no such element is found.

What is first and FirstOrDefault in Linq?

FirstOrDefault works same as First() does, FirstOrDefault returns the first element from a sequence, but here there is an advantage over First(), so if there is no record in the collection which matches input criteria then FirstOrDefault() can handle null values and it does not throw an exception. Conclusion.

What is the difference between first () and FirstOrDefault () Select methods in Linq?

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data.


4 Answers

The generic way to get a default value for a given generic type is:

default(T)

where T is the generic type parameter in question. For reference types, this will yield null. For value types, this will yield a zero'd instance of the value. For DateTimes, this will be equivalent to DateTime.MinValue.

like image 91
Kent Boogaart Avatar answered Sep 24 '22 18:09

Kent Boogaart


DateTime.MinValue

like image 27
Partha Choudhury Avatar answered Sep 24 '22 18:09

Partha Choudhury


default(DateTime) is 1/1/0001 12:00:00 AM.

In your code, the major portion of your query is an IEnumerable of start dates from your database. Your call to FirstOrDefault() is either returning the first element of the enumerable or the default value of its type if there are no elements in the enumerable.

If the type of StartDate is indeed a date and there are no elements in the enumerable, then the result will be the datetime value I provided above.

like image 25
Anthony Pegram Avatar answered Sep 25 '22 18:09

Anthony Pegram


Im guessing its default(DateTime) which im guessing (again) is DateTime.MinValue

like image 23
Jamiec Avatar answered Sep 23 '22 18:09

Jamiec