Dynamic Expressions in the Where Section - Linq to SQL

I am new to LINQ, so hopefully this is not a dumb question:

I have a table with a lot of content presented in a datagrid, and I want the user to be able to filter the grid using some combined fields above the grid [for example, the search bar]

I created a method that takes text in a combo box and puts it in a Where clause:

public void find() { string disName; string statusName; disName = RMcmbDis.Text; //This Get the first string to filter statusName = RMcmbStatus.Text; // this get the second string to filter 

// Here I collect all the necessary data

  var allCNT = from x in cntDB.releases join dis in cntDB.disciplines on x.discipline equals dis.discipline_id join btch in cntDB.batches on x.batch_num equals btch.batch_id join z in cntDB.status on x.status equals z.status_id select new { dis.discipline_name, x.grade, x.batch_num, btch.batch_name, z.status_description, x.segment_leader, x.ped_leader, x.release_location, x.comments, x.QA_Verdict }; 

// Here I do the filtering

  var find = allCNT.Where(a => a.discipline_name == disName && a.status_description == statusName); dataGridView1.DataSource = find; } 

Now I have a problem: I want the user to be able to leave one of the fields with the list empty, and if he does, then he does not want to filter these criteria. [EG - The "RMcmbDis" component has a "Math", and the Status ["RMcmbStatus"] command is empty, so the grid will only show "Math" in all states.

How can I do it? Thanks guys ... N.

+4
source share
2 answers

You can simply add Where() clauses if the condition you want is true ...

 var results = allCNT; if (!string.IsNullOrEmpty(disName)) results = result.Where(a => a.discipline_name == disname); if (!string.IsNullOrEmpty(statusName)) results = results.Where(a => a.status_description == statusName); dataGridView1.DataSource = results; 

See the comment below for one parameter to handle a large number of filters. Another option is to use a helper method:

 T AddFilter<T>(IQueryable<T> results, string filterValue, Expression<Func<T, bool>> predicate) { if(!string.IsNullOrEmpty(filterValue)) return results.Where(predicate); return results; } 

What you will use as follows:

 var results = allCNT; results = AddFilter(results, disname, a => a.discipline_name == disname); results = AddFilter(results, statusName, a => a.status_description == statusName); results = AddFilter(results, whatever, a => a.whatever == whatever); // ... dataGridView1.DataSource = results; 
+6
source

You can add several Where clauses depending on what criteria you have, for example:

 var find = allCNT; if (!string.IsNullOrEmpty(disName)) { find = find.Where(a => a.discipline_name == disName); } if (!string.IsNullOrEmpty(statusName)) { find = find.Where(a.status_description == statusName); } 
+3
source

All Articles