Reputation: 52047
I have a table that has Time1 and Time2 (for the sake of example). Time2 allows for nulls.
I have an object model and I want to have Time2 as nullable; so far I have this:
public Class MyModel{
public DateTime Time1 {get;set;}
public System.Nullable<DateTime> Time2 {get;set}
}
When I go to my query, I have this:
var MyQuery = ...
select new MyModel()
{
Time2 = (a.Time2)
and here I'm wondering if I should have the SingleOrDefault operator? It's not showing in the intellisense. Howver, the intellisense is showing several other options, amongst whic are: HasValue, Value, GetValueOrDefault.
Any ideas on what's the right one to choose from?
Thanks
Upvotes: 3
Views: 36536
Reputation: 1845
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
Upvotes: 4
Reputation: 15242
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.
Upvotes: 2
Reputation: 8726
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
Upvotes: 9