score:9

Accepted answer

That's because Time2 is a nullable type. Nullable types always have a value property. If you revise your line to:

Time2 = (a.Time2).Value

and then press the period symbol after Value, you'll see the Intellisense pop up.

As a safety check you may want to also check that the value of a.Time2 is not null, before using .Value. Otherwise you'll get a null reference exception

score:1

Why do you think that You should have a method that exists for items of a collection on something that is a System.Nullable<DateTime>.

You won't have SingleOrDefault() on this.

Time2 = (a.Time2.HasValue ? a.Time2.Value : null)

That's how you should set the value or have it be null.

score:3

Time2 = a.Time2.HasValue ? a.Time.Value : null;

score:4

SingleOrDefault is a extension method for the generic IEnumerable as you see below.

public static TSource SingleOrDefault( this IEnumerable source)

If you had some list of Nullable you could use that method and it would return the first value or throws if the list had none or more than one item.

//a list of Nullable<DateTime> with exactly 1 item
var listOfDates = new DateTime?[] { null };

var myDate = listOfDates.SingleOrDefault(); // myDate => ((DateTime?)null)

That is probably not what you want, you want some value when it is null, then you should use either the coalesce operator of C# 3.0 or one of the overloads of the GetValueOrDefault method from Nullable<> type.

DateTime? myNullDate = null;

DateTime myDate;
myDate = myNullDate ?? DateTime.Now; // myDate => DateTime.Now
myDate = myNullDate ?? default(DateTime); // myDate => DateTime.MinValue
myDate = myNullDate.GetValueOrDefault(DateTime.Now); // myDate => DateTime.Now
myDate = myNullDate.GetValueOrDefault(); // myDate => DateTime.MinValue

Related Articles