[英]Dynamic LINQ enumerable select
I have the following bool Variables: 我有以下布尔变量:
public bool bCompanyID { get; set; }
public bool bTaxCode { get; set; }
public bool bAccountCode { get; set; }
Depending on which ones are set to true
I set the LINQ expression (this is an example where all three are true : 取决于将哪一个设置为
true
我设置LINQ表达式(这是三个都为true的示例:
System.Collections.Generic.IEnumerable<IP_DataRow> items = null;
items = _vm.Result_Error.Where(n => n.CompanyID == SelectedItem.CompanyID && n.TaxCode == SelectedItem.TaxCode && n.AccountCode == SelectedItem.AccountCode);
What I would like to do (rather than using multiple if statements) is to create this expression dynamically based on the user input. 我要执行的操作(而不是使用多个if语句)是根据用户输入动态创建此表达式。
Is something like this possible, or I simply have to use if statements? 可能会发生这种情况,还是我只需要使用if语句?
EDIT: 编辑:
Here is what came to my mind: 这是我想到的:
items = _vm.Result_Error.Where(n => ((bCompanyID) ? (n.CompanyID == SelectedItem.CompanyID) : true) &&
((bTaxCode) ? (n.TaxCode == SelectedItem.TaxCode) : true) &&
((bAccountCode) ? (n.AccountCode == SelectedItem.AccountCode) : true));
Can I use the above mentioned expression? 我可以使用上述表达方式吗?
Well you can combine then into one using something like this: 那么您可以使用以下方法将其合并为一个:
System.Collections.Generic.IEnumerable<IP_DataRow> items = null;
items = _vm.Result_Error.Where(n => (!bCompanyID || n.CompanyID == SelectedItem.CompanyID)
&& (!bTaxCode || n.TaxCode == SelectedItem.TaxCode)
&& (!bAccountCode || n.AccountCode == SelectedItem.AccountCode));
but an if
statement might be cleaner, especially since you can attach multiple where clauses to an existing query: 但是
if
语句可能更简洁,尤其是因为您可以将多个where子句附加到现有查询中:
items = _vm.Result_Error.AsEnumerable();
if(bCompanyID)
items = items.Where(n => n.CompanyID == SelectedItem.CompanyID);
if(bTaxCode)
items = items.Where(n => n.TaxCode == SelectedItem.TaxCode);
if(bAccountCode)
items = items.Where(n =>n.AccountCode == SelectedItem.AccountCode);
You can combine some conditions with if
statements: 您可以将一些条件与
if
语句结合使用:
var items = _vm.Result.Errors;
if (bCompanyID)
items = items.Where(n => n.CompanyID == SelectedItem.CompanyID);
if (bTaxCode)
items = items.Where(n => n.TaxCode == SelectedItem.TaxCode);
. . .
You can also create single LINQ expression that (as I think) is not so effective: 您还可以创建单个LINQ表达式,但效果不那么理想:
var items = from item in _vm.Result.Errors
where !bCompanyID || item.CompanyID == SelectedItem.CompanyID
where !bTaxCode || item.TaxCode == SelectedItem.TaxCode
. . .
select item;
In the second case the lazy evaluating of &&
and ||
在第二种情况下,
&&
和||
的惰性求值 operators is used, so if bCompanyID
is false
, then right conditions will not evaluating. 使用了运算符,因此如果
bCompanyID
为false
,则不会评估正确的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.