LINQ Where子句中的If条件
我可以在Linq where中使用if子句吗?是,您可以喜欢:LINQ Where子句中的If条件,linq,where,Linq,Where,我可以在Linq where中使用if子句吗?是,您可以喜欢: var query = someList.Where(a => a == "something"); if (condition) { query = query.Where(b => b == "something else"); } var result = query.ToList(); 因为其中正在生成一个IQueryable,执行延迟到我的示例中的ToList,这样您可以将Where链接到一起,然后在
var query = someList.Where(a => a == "something");
if (condition)
{
query = query.Where(b => b == "something else");
}
var result = query.ToList();
因为
其中
正在生成一个IQueryable
,执行延迟到我的示例中的ToList
,这样您可以将Where
链接到一起,然后在通过所有条件后执行它。使用linq中可用的Where
扩展方法
范例
if (SearchControlMain.PostingID.HasValue)
query = query.Where(q => q.PostingID == SearchControlMain.PostingID);
选择下面的,而不是上面的
query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);
我不确定问题是什么,但可能的答案是: 对
不过,这将是一种复杂的简单表达方式。不确定这是否合适,但它非常有用,您可以非常方便地将ifs与条件where子句结合使用:
var r = (from p in productinfo.tblproduct
where p.Accountid == accountid
select p);
if (uuf1 != null)
r = r.Where(p => p.UnitUserField1 == uuf1);
if (uuf2!= null)
r = r.Where(p => p.UnitUserField2 == uuf2);
因此where子句将根据UUF1或UUF2中的内容进行修改,即您可能只有带信息的UUF1,在这种情况下,它将接受该信息并忽略UUF2 where子句,在UUF1或UUF2中可能没有任何内容,而where子句将accountid作为where子句。我曾经遇到过这样一种情况,我必须在列表本身中检查null。这就是我所做的
items = from p in items
where p.property1 != null //Add other if conditions
select p;
// Use items the way you would use inside the if condition
但正如凯尔西指出的那样,这也会起作用-
items = items.Where(a => a.property1 != null);
因此,如果“someCondition”为false,将跳过“Where”。在我的例子中,有两个“conditional”Where取决于搜索键,所以我这样做了:
var query = db.Package.Include("SomeThing")
.Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
.Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
...
这就是如何使用nooblinq语法实现的。
仅当条件2为false时,才应用条件3。
如果condition2为true,则实际上执行的是&&true
,这对where子句没有影响
因此,它基本上是这样做的:
if(condition2)
{
from item in items
where condition1
select item
else
{
from item in items
where condition1
&& condition3
select item
}
这等于:list.Where(item=>Foo(item));哪里不生产IQueryable,哪里就生产IEnumerable。错answer@OmerK实际上product IQueryable在哪里,如果您运行扩展方法的对象也是一个IQueryable,如果您在IEnumerable上运行它,您将得到一个IEnumerable.Analog(略短):
var query=someList.Where(a=>!someCondition | | a==“something”)代码>
var query = db.Package.Include("SomeThing")
.Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
.Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
...
from item in items
where condition1
&& (condition2 ? true : condition3)
select item
if(condition2)
{
from item in items
where condition1
select item
else
{
from item in items
where condition1
&& condition3
select item
}