mickro
mickro

Reputation: 891

Looking for simple way to build Linq dynamic / conditional expression

Given tables as:

Table1

Table2

Given a UI allow user to make fency query on:

And as result datagridview with everyfields.

I want to build conditional query as if not "any" add this condition.

Considering that, simple LINQ query is not applicable:

Table2
  .Where(x => x.stringfield1 == dropdwonlist1.SelectedValue)
  .Where(x => x.stringfield2 == dropdwonlist2.SelectedValue)
  .Where(x => x.stringfield3 == dropdwonlist3.SelectedValue)
(...)

There is Expression trees in documentation but that looks too much.

Is there simplest way to build my dynamic query ?

Upvotes: 4

Views: 959

Answers (3)

Chris Moschini
Chris Moschini

Reputation: 37967

It's common to forget that you can keep building up LINQ expressions across multiple statements. It's one of the great niceties of LINQ. I would simplify dasblinkenlight's answer for the LINQ-to-SQL translation that's going to happen afterward to:

IQueryable<T> query = Table2;

if (dropdownlist1.SelectedValue == null)
    query = query.Where(x => x.stringfield1 == dropdownlist1.SelectedValue);
// etc

That way anything with a null value doesn't get mixed up into the where clauses at all, reducing the chances the generated SQL has unnecessary conditions in it.

I like Donut's answer best as a more generalized solution though - for example LINQKit would let you write a loop over the 6 dropdowns that writes each where clause if necessary.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Expression trees look scarier than they are, but you are right, in your situation they are unnecessary: you could use a static condition that is smart enough to ignore dropdowns that have no selection. You can do it like this:

Table2
.Where(x => dropdwonlist1.SelectedValue == null || x.stringfield1 == dropdwonlist1.SelectedValue)
.Where(x => dropdwonlist2.SelectedValue == null || x.stringfield2 == dropdwonlist2.SelectedValue)
.Where(x => dropdwonlist3.SelectedValue == null || x.stringfield3 == dropdwonlist3.SelectedValue)

Upvotes: 6

Donut
Donut

Reputation: 112845

I've used LINQKit for similar scenarios with great success.

Specifically, you should be able to use the PredicateBuilder to accomplish what you're looking for.

Upvotes: 3

Related Questions