tags:

views:

52

answers:

2

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.

+4  A: 
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
Have you tested this? I'm getting an `InvalidOperationException` when I try to enumerate the result.
C. Ross
Do you have more details on what the error is? What's the error message?
David Morton
@David `{"Nullable object must have a value."}`
C. Ross
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
@David I double checked, but no, that's not the case. All rows are notted, and are internally consistent (`a`,`a`,`a`).
C. Ross
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
Also, out of curiosity, of what type is "row"?
David Morton
+4  A: 
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