带有linq .where子句的null引用异常 [英] null reference exception with linq .where clause

查看:117
本文介绍了带有linq .where子句的null引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个可以为null的对象数组(该数组)中获取一个属性,而我始终会得到一个null引用异常.

I'm trying to get a property from an array of object that can be null (the array) and I'm always getting a null reference exception.

如果它为null或返回空字符串,我如何告诉LINQ不要对其进行处理?

How can I tell LINQ to not process it in case it's null or to return an empty string?

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不要处理数组是否为null.

I've also tried that to not take null. I don't get the mechanism to tell LINQ not to process if the array is null.

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

推荐答案

您可以使用null .aspx> ?:(条件)运算符:

You can check if it's null with ?:(conditional) operator:

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

如果 First 引发异常,因为没有人使用ContactType.PHONE,则可以使用具有自定义默认值的 DefaultIfEmpty :

If First throws an exception because there's no one with ContactType.PHONE you can use DefaultIfEmpty with a custom default value:

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

请注意,由于我已经提供了默认值,因此First现在不能再引发异常.

Note that First now cannot throw an exception anymore since i've provided a default value.

这篇关于带有linq .where子句的null引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆