如何使用动态OR语句构建Linq查询? [英] How can I build Linq query with dynamic OR statements?
问题描述
以下代码:
var dynamicQuery = from a in _context.Users select a;
string[] args = new string[] { "aa", "bb", "cc" };
foreach (string word in args)
dynamicQuery = dynamicQuery.Where(x => x.Name.Contains(word));
return dynamicQuery.ToList();
允许我使用动态列表的 AND 表达式创建Linq查询.
Will allow me to create a Linq query with a dynamic list of AND expressions.
但是假设我只想使用动态列表的 OR 表达式来做到这一点?
But suppose I wanted to do the same, only with a dynamic list of OR expressions?
推荐答案
您根本不需要循环:
return _context.Users.Where(x => args.Any(word => x.Name.Contains(word)));
更一般而言,您可以使用:
More generally, you can use:
Func<User, bool> predicate = user => false;
foreach (var item in items)
{
var predicateCopy = predicate;
predicate = user => predicateCopy(user) || someOtherCondition;
}
return query.Where(predicate);
这将导致非常深的堆栈(一个代表调用另一个代表另一个,以此类推).在特定情况下允许您使用Any
的情况,通常这是一种更好的方法.
This will end up with quite deep stacks (with one delegate calling another calling another etc). Where the specific situation allows you to use Any
, that would usually be a better approach.
我希望Any
在大多数情况下都可以工作,在这些情况下您可能需要匹配的项目集合...非Any
方法适用于在某些情况下,年龄在18岁以上的人都可以...在某些情况下,姓氏以"G"开头的任何人都是合适的,等等.
I would expect Any
to work in most situations where you've got a collection of items to potentially match against... the non-Any
approach is approprate for "in some situations, anyone over 18 is fine... in some situations anyone with a last name beginning with "G" is appropriate, etc.
这篇关于如何使用动态OR语句构建Linq查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!