Null value in linq where clause

c#, linq

Solution

Checking the property is null or empty before comparing it it's the only way I know

if (!string.IsNullOrEmpty(searchString))
      {
          Infos = Infos.Where(
              x =>
              (!String.IsNullOrEmpty(x.FirstName) && x.FirstName.ToLowerInvariant().Contains(searchString)) ||
              (!String.IsNullOrEmpty(x.LastName) && x.LastName.ToLowerInvariant().Contains(searchString)) ||
              (!String.IsNullOrEmpty(x.ContractNum) && x.ContractNum.ToLowerInvariant().Contains(searchString)) ||
              (!String.IsNullOrEmpty(x.VIN) && x.VIN.ToLowerInvariant().Contains(searchString)) ||
              (x.Claim != null && !String.IsNullOrEmpty(x.Claim.InitiatedBy) && x.Claim.InitiatedBy.ToLowerInvariant().Contains(searchString))
              ).ToList();
      }

EXTRA: I added a check on the `Claim` property to make sure it's not null when looking at `InitiatedBy`

EXTRA 2: Using the build in function `IsNullOrEmpty` to compare string to `""` and `null`so the code is clearer.

Extra 3: Used of `ToLowerInvariant` (https://msdn.microsoft.com/en-us/library/system.string.tolowerinvariant(v=vs.110).aspx) so the lowering action will act the same no matter of the culture.

Problem

I'm having an issue where I want to return results where something matches and I get an error if one of the properties I'm trying to match is null. ``` if (!string.IsNullOrEmpty(searchString)) { Infos = Infos.Where( x => x.FirstName.ToLower().Contains(searchString) || x.LastName.ToLower().Contains(searchString) || x.ContractNum.ToLower().Contains(searchString) || x.VIN.ToLower().Contains(searchString) || x.Claim.InitiatedBy.ToLower().Contains(searchString) ).ToList(); } ``` If `ContractNum` or `VIN`, for example, are null then it throws an error. I'm not sure how to check if one of these are null inside of a linq query.

Original source