C. Ross
C. Ross

Reputation: 31848

Linq search that ignores nulls

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.

Upvotes: 5

Views: 266

Answers (2)

Mark Byers
Mark Byers

Reputation: 838186

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)
}

Upvotes: 5

David Morton
David Morton

Reputation: 16505

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;

Upvotes: 4

Related Questions