LINQ的。哪里条款空引用异常(null reference exception with linq

2019-07-18 02:02发布

我试图从对象的数组可以为空(阵列)得到一个属性,我总是得到一个空引用异常。

我怎么能告诉LINQ到的情况下,对其进行处理,这是空或返回一个空字符串?

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

我也试过,不采取空。 我不明白的机制来告诉LINQ不处理,如果数组为空。

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

Answer 1:

你可以检查它是否是null?: (条件)运算符 :

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 ,现在不能再抛出一个异常,因为我提供的默认值。



Answer 2:

试试下面的代码(我假设contactText是一个string )。

你可能想看看你的公共属性名的大写规范所有与大写字母开头。

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


Answer 3:

尝试:

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


Answer 4:

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 
  }

); }



Answer 5:

null值是contactType所以我们增加(ci.contactType != null)

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


文章来源: null reference exception with linq .where clause