Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to get max of nullable datetime from a list

Tags:

c#

linq

Suppose I have a list of object models that look like this:

public class MyModel
{
   public Nullable<DateTime> SomeUserTime { get; set; }
}

var List<MyModel> TheList = some list from somewhere

I want to get the latest SomeUserTime in the list, knowing that may be the list doesn't contain any value, in which case the output should be null. This is what I have:

DateTime? LatestTime = (from x in TheList select x.SomeUserTime).Max();

This compiles fine but the sample data doesn't have any null values. Will this also work (ie return null) if none of the elements in the list have a time?

like image 647
frenchie Avatar asked Oct 11 '25 07:10

frenchie


2 Answers

Yes it will ignore the null values and give you the Max in DateTime?.

List<DateTime?> list = new List<DateTime?>();
list.Add(new DateTime?());
list.Add(new DateTime(2014,04,15));
DateTime? max = list.Max();

and you will get back:

max = {15/04/2014 12:00:00 AM}

You can also filter out null values and then get max like:

DateTime LatestTime = (from x in TheList 
                       where x.SomeUserTime != null) //or x.SomeUserTime.HasValue
                       select x.SomeUserTime.Value).Max();

The above line would throw an exception if the list is empty. You will get:

Sequence contains no elements

You can fix it like:

DateTime? LatestTime = (from x in TheList 
                        select x.SomeUserTime).Max();

If the list is empty then this will give you null, or return you the max date if list contains any DateTime value. Just make sure you are not trying to store the result in DateTime, use Nullable<DateTime> or DateTime? and do not access Value property of Nullable<T> item.

like image 87
Habib Avatar answered Oct 13 '25 21:10

Habib


DateTime? LatestTime = (from x in TheList 
                        select (DateTime?)x.SomeUserTime).Max();
like image 44
Sagi Avatar answered Oct 13 '25 22:10

Sagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!