5

How can I make a linq search that ignores nulls (or nullables)?

I have a method

IEnumerable<X> Search(int? a, int? b, int? c)

And I want it to return matches on any of the ints? that are not null.

IE: if a and c have values 1 and 9 and b is null the search should render (roughly) to

SELECT * 
FROM [TABLE]
WHERE a = 1
AND c = 9

My real method will have 5+ paramters, so iterating combinations is right out.

C. Ross
  • 31,137
  • 42
  • 147
  • 238

2 Answers2

5
IEnumerable<X> query = items;
if (a.HasValue) {
    query = query.Where(x => x.a == a.Value)
}
if (b.HasValue) {
    query = query.Where(x => x.b == b.Value)
}
if (c.HasValue) {
    query = query.Where(x => x.c == c.Value)
}
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
4
var result = from row in table 
where (!a.HasValue || row.a == a.Value)
&& (!b.HasValue || row.b == b.Value)
&& (!c.HasValue || row.c == c.Value)
select row;
David Morton
  • 16,338
  • 3
  • 63
  • 73
  • Have you tested this? I'm getting an `InvalidOperationException` when I try to enumerate the result. – C. Ross Mar 04 '10 at 01:48
  • Do you have more details on what the error is? What's the error message? – David Morton Mar 04 '10 at 02:01
  • @David `{"Nullable object must have a value."}` – C. Ross Mar 04 '10 at 02:04
  • There should be no way that could possibly happen unless you've written your query wrong. If the first half of each "or" couple is evaluated to true, then the second half shouldn't be called. Are you certain you've placed your "!" in front of the proper rows? Also, have you verified that each group is using one variable, that you don't have something like: (!a.HasValue || row.a == b.Value)? – David Morton Mar 04 '10 at 02:13
  • @David I double checked, but no, that's not the case. All rows are notted, and are internally consistent (`a`,`a`,`a`). – C. Ross Mar 05 '10 at 01:44
  • What's your entire stack trace? You may want to append this to your original post and then post back. Something's not adding up here. This situation shouldn't be happening. – David Morton Mar 05 '10 at 03:10
  • Also, out of curiosity, of what type is "row"? – David Morton Mar 05 '10 at 03:10