Home > Software design >  Object property suddenly becomes null when queried with a linq statement
Object property suddenly becomes null when queried with a linq statement

Time:11-25

I have the following linq query:

private List<Port> DoCountriesSearch(string search)
{
    return Countries.Where(x => x.CountrySearch.ToLower().Contains(search.ToLower())).ToList();
}

I have an object called Countries which is a list of Port objects with various properties. Each Port object contains a property called CountrySearch which you can see here:

enter image description here

But as soon as I try to run the linq query on Countries, suddenly the CountrySearch property is null which throws a null reference exception:

enter image description here

I've never had this issue with linq before. What am I missing?

CodePudding user response:

Your list has a lot of entries. In some entries CountrySearch is not null, in others it is null. There is no magic happening with LINQ here.

You can fix this with a Null-conditional operator

private List<Port> DoCountriesSearch(string search)
{
    return Countries.Where(
        x => x.CountrySearch?.Contains(
            search,
            StringComparions.CurrentCultureIgnoreCase) == true
    ).ToList();
}

Note that == true is required here because we have to cope with null values.

See also:

CodePudding user response:

The issue was entirely my fault. I had a buried method that was appending Port objects to the bottom of the list that did not come from the database, therefore the CountrySearch fields for those items were indeed null.

  • Related