Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ new instance when SingleOrDefault returns null

Tags:

c#

asp.net

linq

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.

like image 733
r3plica Avatar asked Dec 30 '12 18:12

r3plica


People also ask

Does single or default return null?

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 .

What exception does SingleOrDefault throw?

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.

Which is better SingleOrDefault or FirstOrDefault?

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.

What is the difference between FirstOrDefault () and SingleOrDefault () extension method in Linq?

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.


2 Answers

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

return _addresses.Where(x => x.TypeId == AddressType.Delivery)
                 .DefaultIfEmpty(new Adress())
                 .Single();
like image 135
Tim Schmelter Avatar answered Oct 19 '22 17:10

Tim Schmelter


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.

like image 38
Olivier Jacot-Descombes Avatar answered Oct 19 '22 16:10

Olivier Jacot-Descombes