问题描述
im在asp.net core v3.1中运行
im running this in asp.net core v3.1
我的问题类似于以下问题:
my question is similar to this question:
How to use Linq to check if a list of strings contains any string in a list
与第一个答案有关的特定问题,使得
with the specific question relating to the first answer such that
filterTags = ["abc", "cd", "efg"]
var results = db.People
.Where(p => filterTags.Any(tag => p.Tags.Contains(tag)));
所以基本上是说
给我所有人数据库的结果
谁的标签字段包含任何filterTags
其中标签=由一堆用空格分隔的标签填充的大文本字段
so basically saying
give me results from the db of all People
who's Tags field contains any of the filterTags
where Tags = a big text field populated by a bunch of space-delimited tags
这似乎很简单(尤其是因为它已经写过了)
但我回来了一个错误
This seems straightforward (esp since this has been written before)
but i get an error back
有人知道这是什么意思还是我做错了什么?
does anyone know what this means or what im doing wrong?
推荐答案
使用纯EF LINQ无法做到这一点.您必须创建帮助程序,该帮助程序可以在表达式树"中转换搜索列表.
This is not possible with pure EF LINQ. You have to create helper which transforms your search list in Expression Tree.
public static class QueryExtensions
{
private static MethodInfo _containsMethodInfo = typeof(string).GetMethod("Contains")!;
public static IQueryable<T> FilterUsingContains<T>(this IQueryable<T> query, Expression<Func<T, string>> prop, IList<string> items)
{
if (items.Count == 0)
return query.Where(e => 1 == 2);
var param = prop.Parameters[0];
var predicate = items.Select(i =>
(Expression)Expression.Call(prop.Body, _containsMethodInfo, Expression.Constant(i, typeof(string))))
.Aggregate(Expression.OrElse);
var lambda = Expression.Lambda<Func<T, bool>>(predicate, param);
return query.Where(lambda);
}
}
然后您可以在查询中使用此扩展名
Then you can use this extension in your queries
filterTags = ["abc", "cd", "efg"]
var results = db.People
.Where(p => p.Tags.AsQueryable().FilterUsingContains(t => t, filterTags).Any());
这篇关于使用linq查找文本字段是否在列表中包含任何字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!