0

When filtering a list using lambda where and contains, I get a NullReference error

var servers = _context.Servers.ToList();
servers = servers.Where(t => t.Technology.Contains(technology)).ToList();

But I get a this error:

Exception thrown: 'System.NullReferenceException' in ServerBuildApp.dll ServerBuildApp.Models.Servers.Technology.get returned null.

The list of servers contains a 'Technology' property and it contains the string I am passing it, for example "BIZ"

Any ideas? Or am I doing this completely wrong?

Gareth Doherty
  • 187
  • 1
  • 3
  • 15
  • 1
    The title of question and the question itself has nothing to do with each other. Apparently you have at least one element in the list whose `Technology` property is null. – Ofir Winegarten Dec 19 '18 at 11:32
  • You are not exactly "filtering in place without creating a new list", more like "filtering and creating a new list, but assigning it to the same variable" - which is not a problem, just to keep things accurate. As for the error - it's not related, you just have some `Technology` properties with a value of `null` - check for it before you call a function on the value (e.g. `t.Technology?.Contains(technology)`) – Nimrod Dolev Dec 19 '18 at 11:32
  • I have updated the question and the content to represent the real problem, thanks for everyone's quick responses. Love this community. – Gareth Doherty Dec 19 '18 at 12:00

1 Answers1

4

You need to check the t.Technology for null.

var servers = _context.Servers.ToList();
servers = servers.Where(t => t.Technology?.Contains(technology) is true).ToList();

You should check t.Technology for null and then check it contains.

lindexi
  • 4,182
  • 3
  • 19
  • 65