0

I have a linq query such as

.where(x => (x.Title.Contains(text) || x.Comments.Contains(text)))

If I run the code and the first part (x.Title.Contains(text)) has a hit, the code runs fine... if I run the code and the first part wouldn't have a hit... it seems the second part is blowing up and causing an exception now. I'm specifically getting a null reference exception.

It's like the first part of the query is stripping the set down to nothing, and the second part is attempting to query against that? That's the cause for the exception?

Or might I have a problem elsewhere in the code and the linq query is actually fine?

  • `x.Comments` is null? – trailmax May 21 '19 at 22:23
  • If you're getting a null reference exception, then it's likely that `x.Comments` is null. It passes the first part because it's an `or` query, there's no point checking it. – DavidG May 21 '19 at 22:24
  • You can't call methods on `null` objects, so if `Title` or `Comments` is `null`, then calling `Contains` will throw an exception. You can check for null first, or use null-coalescing operators: `.Where(x => (x.Title?.Contains(text) ?? false || x.Comments?.Contains(text) ?? false))` – Rufus L May 21 '19 at 22:31
  • So the issue seems to be then that if I try to use x.Comments?.Contains(text) ?? false.... it's a C# 6 feature and I can't use that.... – Brandon Kick May 22 '19 at 00:08
  • Solved it.... x.title.Contains(text) || x.comments != null && x.comments.contains(text) – Brandon Kick May 22 '19 at 00:15

0 Answers0