linq.where子句的null引用异常



我试图从一个可以为null的对象数组(数组(中获取一个属性,但我总是得到一个null引用异常。

我如何告诉LINQ在它为null的情况下不处理它,或者返回一个空字符串?

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。如果数组为null,我没有告诉LINQ不要处理的机制。

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

您可以使用?:(条件(运算符检查它是否为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现在不能再抛出异常了,因为我已经提供了一个默认值。

尝试下面的代码(我假设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
        });
}

尝试:

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

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

    var phone = c.address.contactItems.Where( ci => (ci.contactType != null) && ci.contactType == ContactType.PHONE).First().contactText
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 
  }

);}

避免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();

这是给我的!

相关内容

  • 没有找到相关文章

最新更新