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:
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:
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:
- Best way to check for nullable bool in a condition expression.
- StringComparison Enum for possible values.
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.