0

How do I correctly write this LINQ statement? I have this list (outfalls) of class Outfall. It works without the WHERE clause. When I added the WHERE it throws a NullReferenceException.

outfalls = outfalls
    .Select(x => new Outfall { loc_name = x.sys_loc_code, planned_task_code = x.planned_task_code })
    .Where(x => x.planned_task_code.Contains("DAILY"))
    .ToList();
John Doe
  • 1,950
  • 9
  • 32
  • 53
  • 2
    Your `Select` returns an `IEnumerable`, where each `Outfall` only has its `loc_name` field populated. Thus, `planned_task_code` is null and calling `Contains` throws the exception appropriately. – Heretic Monkey Apr 22 '19 at 18:55
  • @HereticMonkey Why not post that as an answer instead of a comment? – Ethan The Brave Apr 22 '19 at 18:57
  • 1
    @EthanTheBrave Did you see the second comment, where I say the question is a duplicate? One should not answer duplicate questions. Now it's been closed as such. – Heretic Monkey Apr 22 '19 at 18:58
  • ah I modified it to set the planned_task_code but it's still throwing the same error. please see the updated question – John Doe Apr 22 '19 at 18:58
  • If `x.planned_task_code` is `null`, you'll still get the exception – Rufus L Apr 22 '19 at 18:59
  • You can modify your code to check for `null`, like: `.Where(x => x.planned_task_code != null && x.planned_task_code.Contains("DAILY"))` or simply: `.Where(x => x.planned_task_code?.Contains("DAILY") ?? false)` – Rufus L Apr 22 '19 at 19:03
  • @HereticMonkey I did not. That makes more sense then! :) – Ethan The Brave Apr 22 '19 at 19:08
  • 1
    @PauloCampez If `x.planned_task_code` is `null`, then calling `Contains` on it will throw an exception. Also, `("DAILY" ?? string.Empty).ToString()` doesn't do anything to change the existing code at all. `"DAILY"` is not `null`, so `string.Empty` will never be used. Also, no need to call `ToString()` on a `string`. – Rufus L Apr 22 '19 at 19:08

0 Answers0