简体   繁体   中英

Linq to Datatable with multiple where clauses

Situation: Linq query to datatable with multiple where clauses. The filter for the where clause comes from several ComboBoxes like account, year, month, etc. The result of the query will be saved into a different datatable.

I have different queries like...

        //Filter Year
            var query = from myRow in ds.Tables["tblOriginal"].AsEnumerable()
                        where myRow.Field<DateTime>("Datum").Year == int.Parse(cmbFilterYear.Text)
                        select myRow;
            ds.Tables["tblFilteredData"].Merge(query.CopyToDataTable());

... I have about six of these Linq queries which I want to have in one single query with different where clauses using

...&&...

It works if all ComboBoxes are filled with values.

But it won't work if eg only 4 of 6 ComboBoxes are filled with values.

Is there a possibility to put an "IF..." into the "where"-block of the query?

I have already tried to use a stringbuilder to set a variable for the where clause but I can't convert it into a proper boolean.

Any idea is appreciated.

Use method syntax instead. It allows you to build query step-by-step:

var query = ds.Tables["tblOriginal"].AsEnumerable();

int year;
if (Int32.TryParse(cmbFilterYear.Text, out year)) // condition for adding filter
    query = query.Where(r => r.Field<DateTime>("Datum").Year == year);

// repear for other conditions

ds.Tables["tblFilteredData"].Merge(query.CopyToDataTable()); // execute query

If you dont want to use the method syntax way (as shown by @lazyberezovsky), you can try something like below:

//Filter Year
var query = from myRow in ds.Tables["tblOriginal"].AsEnumerable()
            where (string.IsNullOrEmpty(cmb1.Text) || myRow.Field<DateTime>("Datum").Year == int.Parse(cmb1.Text))
               && (string.IsNullOrEmpty(cmb2.Text) || myRow.Field<DateTime>("Datum").Year == int.Parse(cmb2.Text))
               && (string.IsNullOrEmpty(cmb3.Text) || myRow.Field<DateTime>("Datum").Year == int.Parse(cmb3.Text))
            select myRow;
ds.Tables["tblFilteredData"].Merge(query.CopyToDataTable());

Here, string.IsNullOrEmpty(cmb1.Text) is your non-value condition. If emptyness is not the correct non-value condition for your case, replace it with whatever suites your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM