LINQ to SQL handling nulls
What is the best way to deal with null values in Linq.
I have this code which retrieves the customer contacts from the db but if the contact details don't exist it creates a new instance
void SetProperty(int _CustomerID)
{
Contacts_GetResult Contact;
if (Global.VariableStore._Contact == null)
{
Contact = Cd.Contacts_Get(_CustomerID).SingleOrDefault();
if (Contact == null)
Contact = new Contacts_GetResult();
Global.Var开发者_高级运维iableStore._Contact = Contact;
}
else
{
Contact = Global.VariableStore._Contact;
}
if (Contact != null)
{
HomeNumber.Value = Contact.HomeNumber.ToString();
MobileNumber.Value = Contact.MobileNumber.ToString();
WorkNumber.Value = Contact.WorkNumber.ToString();
EmailAddress.Value = Contact.EmailAddress.ToString();
}
When it create the new contacts all the values are null which makes the below code fail as the value is null
HomeNumber.Value = Contact.HomeNumber.ToString();
I currently use:
if (Contact.HomeNumber != null)
HomeNumber.Value = Contact.HomeNumber.ToString();
Is there an easier way?
There is a number of ways, all of which include checking for null one way or the other:
if (Contact.HomeNumber != null)
HomeNumber.Value = Contact.HomeNumber.ToString();
HomeNumber.Value = (Contact.HomeNumber ?? string.Empty).ToString();
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: string.Empty;
There is a slight difference in that the last two samples will substitute the null value with an empty string. In the case of the ??
operator, there is nothing much to do about that; that whole code construct is about making sure that the value is not null before operating on it. That code is the most compact of them, but comes with the downside of unnecessary calls to ToString
when HomeNumber
is null
.
In the case of the ?:
operator, that sample can easily be altered to return null instead of an empty string:
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: null;
I use the following extension method to (somewhat) simplify guarding against null instances:
public static V ValueOrDefaultIfNull<T, V>(this T @this, Func<T, V> @value, V @default)
{
return @this != null ? @value(@this) : @default;
}
So now I can make calls like this:
HomeNumber.Value = Contact.ValueOrDefaultIfNull(x => x.HomeNumber.ToString(), "N/A");
精彩评论