Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for simple way to build Linq dynamic / conditional expression

Tags:

c#

linq

Given tables as:

Table1

  • id
  • stringfield1
  • stringfield2
  • stringfield3
  • stringfield4

Table2

  • id
  • table1_id
  • stringfield1
  • datefield1

Given a UI allow user to make fency query on:

  • dropdwonlist1 with any and table1.stringfield1 values
  • dropdwonlist2 with any and table1.stringfield2 values
  • dropdwonlist3 with any and table1.stringfield3 values
  • dropdwonlist4 with any and table1.stringfield4 values
  • dropdwonlist5 with any and table2.stringfield1 values
  • dropdwonlist6 with [any, the, before, after, between]
  • calendar1 to link with table2.datefield1
  • calendar2 to link with table2.datefield1

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 ?

like image 850
mickro Avatar asked Aug 31 '25 01:08

mickro


1 Answers

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)
like image 163
Sergey Kalinichenko Avatar answered Sep 02 '25 13:09

Sergey Kalinichenko