linq .where子句的null引用exception

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

如果它为null或返回空字符串,我怎么能告诉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。 如果数组为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抛出exception,因为没有人使用ContactType.PHONE您可以将DefaultIfEmpty与自定义默认值一起使用:

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

请注意, First现在不能再抛出exception,因为我提供了一个默认值。

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

尝试:

 var contact = c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).FirstOrDefault(); phone = contact != null ? contact.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 } 

); }

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

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