LINQ new instance when SingleOrDefault returns null

You could use DefaultIfEmpty and use that instance as default value:

return _addresses.Where(x => x.TypeId == AddressType.Delivery)
                 .DefaultIfEmpty(new Adress())
                 .Single();

You could create your own extension method, like this:

public static T NewIfNull<T>(this T obj) where T: class, new()
{
   return obj ?? new T();
}

... then tack a usage onto the end of SingleOrDefault:

var singleResult = myCollection.SingleOrDefault().NewIfNull();

... or because the logic is so simple, just inline it as other answers have said.


Instead of

return _addresses.SingleOrDefault(x => x.TypeId == AddressType.Delivery);

Do something like this:

var address = _addresses.SingleOrDefault(x => x.TypeId == AddressType.Delivery);

if(address == null)
    address = new Address();

return address;

Use the null-coalescing operator:

return _addresses
    .SingleOrDefault(x => x.TypeId == AddressType.Delivery) ?? new Address();

The expression

x ?? y

yields x if x is not null, otherwise y. You can chain the operator

x ?? y ?? z ?? t

This returns the first non-null value or null if all of them are null.


UPDATE

Note that SingleOrDefault throws an exception if the sequence has more than one element. If you need the first element of a sequence possibly having no or more than one element, use FirstOrDefault instead.

Tags:

C#

Linq

Asp.Net