C# 具有多个where子句的Linq到Datatable

C# 具有多个where子句的Linq到Datatable,c#,linq,C#,Linq,情况: 使用多个where子句对datatable进行Linq查询。 where子句的过滤器来自几个组合框,如account、year、month等。 查询结果将保存到不同的数据表中 我有不同的疑问,比如 //Filter Year var query = from myRow in ds.Tables["tblOriginal"].AsEnumerable() where myRow.Field<Da

情况: 使用多个where子句对datatable进行Linq查询。 where子句的过滤器来自几个组合框,如account、year、month等。 查询结果将保存到不同的数据表中

我有不同的疑问,比如

        //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());
如果所有组合框都填充了值,则该选项有效

但是,如果6个组合框中只有4个填充了值,则它将不起作用

是否有可能在查询的“where”-块中输入“IF…”

我已经尝试使用stringbuilder为where子句设置变量,但无法将其转换为正确的布尔值


任何想法都值得赞赏。

请改用方法语法。它允许您逐步构建查询:

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
var query=ds.Tables[“tblOriginal”].AsEnumerable();
国际年;
if(Int32.TryParse(cmbFilterYear.Text,out year))//添加过滤器的条件
query=query.Where(r=>r.Field(“数据”).Year==Year);
//其他条件下的repear
ds.Tables[“tblfilteredata”].Merge(query.CopyToDataTable());//执行查询

如果不想使用方法语法方式(如@lazyberezovsky所示),可以尝试以下方法:

//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());
//过滤年
var query=来自ds.Tables[“tblOriginal”].AsEnumerable()中的myRow
其中(string.IsNullOrEmpty(cmb1.Text)| | myRow.Field(“基准”).Year==int.Parse(cmb1.Text))
&&(string.IsNullOrEmpty(cmb2.Text)| | myRow.Field(“数据”).Year==int.Parse(cmb2.Text))
&&(string.IsNullOrEmpty(cmb3.Text)| | myRow.Field(“数据”).Year==int.Parse(cmb3.Text))
选择myRow;
ds.Tables[“tblfilteredata”].Merge(query.CopyToDataTable());
这里,
string.IsNullOrEmpty(cmb1.Text)
是非值条件。如果清空不是您的案例的正确无值条件,请用您需要的任何东西替换它

//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());