Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq search that ignores nulls

Tags:

c#

linq-to-sql

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.

like image 551
C. Ross Avatar asked Mar 04 '10 01:03

C. Ross


2 Answers

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)
}
like image 61
Mark Byers Avatar answered Oct 15 '22 14:10

Mark Byers


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;
like image 40
David Morton Avatar answered Oct 15 '22 13:10

David Morton