Niklas
Niklas

Reputation: 13135

Select statement to prevent selecting null

I have a model where Person has 0, 1 or 2 Contact objects.
Contact information home (contact_type is "h") and contact information for work (contact_type is "w").

Is there a way to check that the Contact object with contact_type == "h" exists when selecting street name? Right now I'm getting a null exception if the Contact object does not exist.

from m in persons
select new
{
    Id = m.id,
    Name = m.surname,
    Address = m.Contacts.Where(c => c.contact_type == "H").SingleOrDefault().streetname
};

Upvotes: 1

Views: 334

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062745

How about:

var rows = from m in persons
    let h = m.Contacts.Where(c => c.contact_type == "H").SingleOrDefault()
    select new {
        Id = m.id,
        Name = m.surname,
        Address = (h == null ? null : h.streetname)
    };

or:

var rows = from m in persons
    select new {
        Id = m.id,
        Name = m.surname,
        Address = m.Contacts.Where(c => c.contact_type == "H")
                 .Select(c => c.streetname).SingleOrDefault()
    };

which could also be written (perhaps more clearly):

var rows = from m in persons
    select new {
        Id = m.id,
        Name = m.surname,
        Address = (from c in m.Contacts
                   where c.contact_type == "H"
                   select c.streetname).SingleOrDefault()
    };

Upvotes: 3

Nick Butler
Nick Butler

Reputation: 24383

You can have mulitple Where clauses:

Address = m.Where( person => person.Contacts != null ).Contacts.Where( ...

Upvotes: 0

Related Questions