null reference exception with linq .where clause

27,141

Solution 1

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 

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 

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

Solution 2

Try the code below (I've assumed that contactText is a string).

You may want to look at standardising the capitalisation of your public property names to all start with an upper-case letter.

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

Solution 3

the null value is contactType so we add (ci.contactType != null)

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

Solution 4

Try:

var contact = c.address.contactItems.Where( ci => ci.contactType == ContactType.PHONE).FirstOrDefault();
 phone = contact != null ? contact.contactText : "";
Share:
27,141
Arno 2501
Author by

Arno 2501

I'm a sotware engineer building software for the web for more than 10 years.

Updated on July 09, 2022

Comments

  • Arno 2501
    Arno 2501 almost 2 years

    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.

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

    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
    
  • Arno 2501
    Arno 2501 over 11 years
    I cannot declare var inside the new Response {} statement
  • Arno 2501
    Arno 2501 over 11 years
    Yeah it's good but what if it's not null and that it cannot find an item which has a contactType == PHONE ?
  • Hamlet Hakobyan
    Hamlet Hakobyan over 11 years
    From OP in case it's null or to return a empty string ""
  • Renatas M.
    Renatas M. over 11 years
    And to prevent other exceptions use FirstOrDefault(); and check for null result, instead of Where().First();
  • Eonasdan
    Eonasdan over 11 years
    .Where and .FirstOrDefault is redundant in this case and could be simplified
  • Arno 2501
    Arno 2501 over 11 years
    Thanks a lot that's exactly what I wanted !!! the all thing PLUS DefaultIfEmpty !
  • J. Steen
    J. Steen over 11 years
    No, but you can do it outside, in the scope of the foreach.
  • Adrian Thompson Phillips
    Adrian Thompson Phillips over 11 years
    If you removed the Where and FirstOrDefault it wouldn't work. Can you expand on your comment?
  • Eonasdan
    Eonasdan over 11 years
    could be c.address.contactItems.FirstOrDefault(ci => ci.contactType == ContactType.PHONE).Select(ci => ci.contactText) (I think, didn't test but should be correct)
  • Adrian Thompson Phillips
    Adrian Thompson Phillips over 11 years
    Close, but if you FirstOrDefault first you run the risk of then later trying to Select a property from a null object.
  • mdhameed
    mdhameed almost 3 years
    This works in my case as well. Thanks. But First() vs FirstOrDefault(), which one to prefer; any suggestions please?
  • Tim Schmelter
    Tim Schmelter almost 3 years
    @mdhameed they are same, difference is that First throws an exception if there is no item and FirstOrDefault returns the default value in that case(null for reference types). So use First when you are sure that there's at least one(like in my answer with DefaultIfEmpty).