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.
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)
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With