选择语句以防止选择null

时间:2011-10-24 08:58:55

标签: c# .net linq

我有一个模型,其中Person有0,1或2个Contact个对象 联系信息主页(contact_type为“h”)和工作联系信息(contact_type为“w”)。

选择街道名称时,有没有办法检查Contact contact_type == "h"对象是否存在?现在,如果Contact对象不存在,我将得到一个null异常。

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

2 个答案:

答案 0 :(得分:3)

怎么样:

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)
    };

或:

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()
    };

也可以写(也许更清楚):

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()
    };

答案 1 :(得分:0)

您可以拥有多个Where子句:

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