LINQ Where 子句中的 If 条件
使用 Linq,我可以在 Where
扩展方法中使用条件语句吗?
With Linq, can I use a conditional statement inside of a Where
extension method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
因此,如果 'someCondition' 为 false,则将跳过 'Where'。
so, if 'someCondition' is false, 'Where' will be skipped.
是的,您可以喜欢:
因为
Where
正在生成IQueryable
,因此执行会推迟到我的示例中的ToList
,以便您可以链接只要你想要的,就在一起,然后在通过所有条件后执行它。
Yes you can like:
Because
Where
is producing anIQueryable
, the execution is deferred until theToList
in my example so you can chainWhere
s together as much as you want and then just execute it after you have passed all your conditions.中使用
WhereIf
扩展方法,在 linq示例
而不是上面的示例,请使用下面的
LINQWhereIf扩展方法
LINQ to SQLWhere子句可选条件
Make use of
WhereIf
extenstion method avaialbe in linqExample
instead of above go for the below
LINQ WhereIf Extension Method
LINQ to SQL Where Clause Optional Criteria
不确定这是否合适,但它非常有用,您可以非常方便地将 if 与条件 where 子句一起使用:
因此,where 子句将根据 UUF1 或 UUF2 中的内容进行修改,即您可能只有带信息的 UUF1,在这种情况下它将接受并忽略 UUF2 where 子句,您可能同时拥有两个,其中它将同时接受两个,或者您可能在 UUF1 或 2 中没有任何内容,并且您的 where 子句将仅将 accountid 作为 where 子句。
Not sure if this is appropriate but it is quite useful, you can use ifs quite handily with conditional where clauses:
So the where clause will be amended according to what is in UUF1 or UUF2 i.e. you might have only UUF1 with info, in which case it will take that and ignore the UUF2 where clause, you might have both in which it will take both or you might not have anything in UUF1 or 2 and your where clause will just take the accountid as the where clause.
就我而言,有两个“条件”取决于搜索键,所以我这样做了:
In my case there were two "conditional" where depending on search keys, so I did:
这就是如何使用 noob Linq 语法来做到这一点。
仅当条件 2 为假时才应用条件 3。
如果条件2为真,你实际上是在做
&& true
对 where 子句没有影响。所以它本质上是这样做的:
This is how can you can do it with the noob Linq syntax.
This applies the condition3 only if condition2 is false.
If condition2 is true, you are essentially doing
&& true
which has no effect on the where clause.So it is essentially doing this:
我遇到过这样的情况,我必须检查列表本身是否为空。这就是我所做的。
但正如凯尔西指出的那样,这也行得通——
I had a scenario like this where I had to check for null within the list itself. This is what I did.
But as Kelsey pointed out this would work too -
我不确定问题是什么,但可能的答案可能是:
是的,
尽管如此,这会是一种说简单事情的复杂方式。
I'm not sure what the question is, but a possible answer could be:
Yes,
It would be a complicated way of saying something simple, though.
就我而言,我想保留符合我标准的元素,并记录不符合我标准的元素,而无需多次迭代。
每当您想要对每个元素执行副作用(例如日志记录)时,将 lambda 分解到语句主体中就可以轻松推理。
In my case, I wanted to keep the elements which met my criteria and log the ones that didn't without iterating multiple times.
Any time you want to do a side-effect per element (such as logging), breaking out the lambda into a statement body makes it easy to reason about.