7

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

我如何告诉 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 
      }
   );
}

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

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

6 回答 6

13

您可以检查它是否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现在不能再抛出异常,因为我提供了默认值。

于 2013-01-10T14:26:03.400 回答
2

试试下面的代码(我假设contactText是 a 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
        });
}
于 2013-01-10T14:29:53.537 回答
1

尝试:

var contact = c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).FirstOrDefault();
 phone = contact != null ? contact.contactText : "";
于 2013-01-10T14:23:47.017 回答
1

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

    var phone = c.address.contactItems.Where( ci => (ci.contactType != null) && ci.contactType == ContactType.PHONE).First().contactText
于 2013-01-10T14:25:02.783 回答
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 
  }

); }

于 2013-01-10T14:22:51.400 回答
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();

这个对我有用!

于 2021-03-09T06:55:29.077 回答