动态Linq包含多个值 [英] Multiple Values Contains with Dynamic Linq
问题描述
如何在Dynamic Linq中将多值"与包含"一起使用.
How to use Multiple value with Contain in Dynamic Linq.
与Normal Linq一起使用:
using System;
using System.Linq;
public class Simple {
public static void Main() {
string[] names = { "Burke", "Laptop", "Computer",
"Mobile", "Ahemed", "Sania",
"Kungada", "David","United","Sinshia" };
string[] vars = {"i","a"};
var query = names.Where(i=> vars.Any(j=>i.Contains(j))).ToList();
Console.WriteLine(query.Count);
}
}
期望的SQL
SELECT * FROM User WHERE (NAME LIKE '%a%'OR NAME LIKE '%b%')
尝试过动态Linq:
query = query.Where("new[]{\"a\",\"c\"}.Any(i=>i.Contains(it.ProductName))");
返回异常:
No property or field 'ProductName' exists in type 'String'
依赖项:
- .NET CORE 2.2
- EntityFramework Core 2.2.6
- System.Linq.Dynamic.Core 1.0.18( https://github.com/StefH/System.Linq.Dynamic.Core)
推荐答案
尝试动态查询"有两个问题:
There are two issues with your "tried dynamic query":
-
在转换为动态查询时,您混合了变量名称,因为
i
和j
太相似了.
它
含糊,因为有2个lambda,因此将其解析为最里面的lambda的参数.
it
is ambigous as there are 2 lambdas and so it is parsed as a parameter of the innermost lambda.
我们首先将 i
重命名为 p
(用于产品名称"),将 j
重命名为 s
(用于搜索"):
Let's first rename i
to p
(for "product names") and j
to s
(for "search"):
var query = names.Where(p => vars.Any(s => p.Contains(s))).ToList();
然后,您可以将其直接转换为动态Linq表达式:
Then you can directly transform this to a dynamic Linq expression:
// The type of vars needs to be IEnumerable<string> otherwise Dynamic Linq does not see .Any
IEnumerable<string> vars = new[] {"i", "a"};
var query2 = names.Where("p => @0.Any(s => p.Contains(s))", vars).ToList();
然后,您可以将内部Lambda的参数替换为 it
Then you can replace the argument of inner lambda (s) with it
var query3 = names.Where("p => @0.Any(p.Contains(it))", vars).ToList();
如您所见,您混合了 Contains
的对象和参数.
As you can see you mixed up the object and argument of Contains
.
然后,您可以将表达式应用于EF查询.因此,参数 p
的用法将变为 p.ProductName
:
Then you can apply the expression the EF query. So usage of argument p
becomes p.ProductName
:
IEnumerable<string> vars = new[] {"i", "a"};
query = query.Where("p => @0.Any(p.ProductName.Contains(it))", vars).ToList();
或者像这样:
IEnumerable<string> vars = new[] {"i", "a"};
query = query.Where("p => @0.Any(s => p.ProductName.Contains(s))", vars).ToList();
这篇关于动态Linq包含多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!