linq .where子句的null引用异常

时间:2013-01-10 14:20:13

标签: c# arrays linq null

我正在尝试从一个可以为null(数组)的对象数组中获取属性,并且我总是得到一个空引用异常。

如果LINQ为null或返回空字符串,我如何告诉它不处理它?<​​/ p>

foreach (Candidate c in candidates) {
   results.Add(new Person 
      { 
         firstName = c.firstname, //ok
         lastName = c.Name, //ok

         // contactItems is an array of ContactItem
         // so it can be null that's why I get null exception 
         // when it's actually null
         phone = c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).First().contactText 
      }
   );
}

我也尝试过不取空。如果数组为null,我没有得到告诉LINQ不处理的机制。

phone = c.address.contactItems.Where( ci => ci != null && ci.contactType == ContactType.PHONE).First().contactText

6 个答案:

答案 0 :(得分:11)

您可以使用?:(conditional) operator检查null是否为<{1}}:

phone = c.address.contactItems == null ? ""
    : c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).First().contactText 

如果First引发异常,因为没有人ContactType.PHONE,您可以将DefaultIfEmpty与自定义默认值一起使用:

c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE)
                      .DefaultIfEmpty(new Contact{contactText = ""})
                      .First().contactText 

请注意,First现在不再抛出异常,因为我提供了默认值。

答案 1 :(得分:2)

尝试下面的代码(我假设contactTextstring)。

您可能希望查看标准化公共属性名称的大小写,以大写字母开头。

foreach (Candidate c in candidates) {
    string contactText =
        c.address.contactItems
            .Where(ci => ci.contactType == ContactType.PHONE)
            .Select(ci => ci.contactText)
            .FirstOrDefault()

    results.Add(
        new Person 
        { 
            firstName = c.firstname,
            lastName = c.Name,
            phone = contactText ?? string.Empty
        });
}

答案 2 :(得分:1)

尝试:

var contact = c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).FirstOrDefault();
 phone = contact != null ? contact.contactText : "";

答案 3 :(得分:0)

foreach (Candidate c in candidates) {
results.Add(new Person 
  { 
     firstName = c.firstname, //ok
     lastName = c.Name, //ok

     // contactItems is an array of ContactItem
     // so it can be null that's why I get null exception 
     // when it's actually null
     phone = c.address.contactItems == null
          ? string.Empty
          :c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).First().contactText 
  }

); }

答案 4 :(得分:0)

null值为contactType,因此我们添加(ci.contactType != null)

    var phone = c.address.contactItems.Where( ci => (ci.contactType != null) && ci.contactType == ContactType.PHONE).First().contactText

答案 5 :(得分:0)

避免 linq 中的参数 null 异常,如下所示

 Summaries = (from r in Summaries
              where r.Contains(SearchTerm)
              orderby r
              select r).ToArray();

在这种情况下,如果 null 传递给 searchTerm,您可以检查如下所示的 null 表达式

 Summaries = (from r in Summaries
              where string.IsNullOrEmpty(SearchTerm) ||r.Contains(SearchTerm)
              orderby r
              select r).ToArray();

这对我有用!