I have this simple method:
#region Fields
private Collection<Address> _addresses;
#endregion
#region Public methods
public Address DeliveryAddress()
{
if (_addresses == null)
if (this.Id > 0)
_addresses = Core.Data.Addresses.GetClient(this.Id);
return _addresses.SingleOrDefault(x => x.TypeId == AddressType.Delivery);
}
public Address InvoiceAddress()
{
if (_addresses == null)
if (this.Id > 0)
_addresses = Core.Data.Addresses.GetClient(this.Id);
return _addresses.SingleOrDefault(x => x.TypeId == AddressType.Invoice);
}
#endregion
As you can see I trying to return one result for a DeliveryAddress
and one result for an InvoiceAddress
. My problem is that I would like the link expression to create a new instance of Address()
if SingleOrDefault
returns null
.
I am really new to linq, so I am not sure whether SingleOrDefault
is the correct expression I should be using.
SingleOrDefault Method Does not throw a exception. SingleOrDefault method querying for the product Football , which does not exist in the database. It does not throw any exception. The method returns the default value, which is NULL .
SingleOrDefault<TSource>(IEnumerable<TSource>) Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
SingleOrDefault() Vs. FirstOrDefault() in LINQ QuerySingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
You could use DefaultIfEmpty
and use that instance as default value:
return _addresses.Where(x => x.TypeId == AddressType.Delivery)
.DefaultIfEmpty(new Adress())
.Single();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With