8

I am working on a project where I use Linq for fetching data. Now I have a scenario where I have to check field value contains given string for that I use Contains() function.

Everything works fine, But when any of the field is null then it creates a problem.

personData = personData.Where(x => x.FirstName.ToLower().Contains(q.ToLower()) || x.LastName.ToLower().Contains(q.ToLower())).Select(x => x).ToList();

Here when FirstName or LastName field have a null value it throw an error.

So, how can I overcome from this problem ?

Jigarb1992
  • 828
  • 2
  • 18
  • 41

5 Answers5

7

Use following approach: x.FirstName?.Contains(substring) ?? false

Since C# 6 you can use null-conditional operators, that simplifies some queries greatly. You can read more about this topic here

Yury Glushkov
  • 711
  • 6
  • 16
7

Please try this

personData = personData.Where(x => (x.FirstName != null && x.FirstName.ToLower().Contains(q.ToLower())) ||  (x.LastName != null && x.LastName.ToLower().Contains(q.ToLower()))).Select(x => x).ToList();
Ahmar
  • 3,717
  • 2
  • 24
  • 42
4

You must check first if required values are null, Try using the null-coalescing operator...

personData = personData.Where(x => ((x.FirstName.ToLower() ?? "").Contains(q.ToLower())) ||  ((x.LastName.ToLower() ?? "").Contains(q.ToLower()))).Select(x => x).ToList();
Rahul Hendawe
  • 902
  • 1
  • 14
  • 39
  • It throw error "Operator '&&' cannot be applied to operands of type 'string' and 'bool'" @RahulHendawe – Jigarb1992 Jan 06 '17 at 11:57
  • 1
    Great! it is an better way to handle such situation where if you get any `null` value then those values were replaced by _blank value :) – Rahul Hendawe Jan 06 '17 at 12:07
1

What about using a simple string extension like the following:

public static string AsNotNull(this string value)
{
    if (string.IsNullOrWhiteSpace(value))
        return string.Empty;

    return value;
}

And then use it like:

x.FirstName.AsNotNull()
Dscoduc
  • 7,714
  • 10
  • 42
  • 48
  • Likewise, to avoid `null` when you expect a list, you can add a 2nd extension as overload from [this](https://stackoverflow.com/a/3088169/1016343) answer. Then, use it in the same way, i.e. `.Select(x => x).AsNotNull().ToList();`. With both extensions, one for strings, one for enumerables, you are well armed! – Matt Jul 26 '21 at 13:50
-1

I think you should prevent ability to add null FirstName or LastName at the beggining. This kind of row seems unuseful.

  • this is good suggestion. because if both FirstName and LastName could be null then whats the point of having names? I suggest put `""` instead of null if FirstName or LastName has to be empty – M.kazem Akhgary Jan 06 '17 at 11:46
  • the code I have written in my question is just for example in actual there may be any field/s. – Jigarb1992 Jan 06 '17 at 11:52