使用linq查找文本字段是否在列表中包含任何字符串 [英] using linq to find if a text field contains any string in a list

查看:59
本文介绍了使用linq查找文本字段是否在列表中包含任何字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

System.InvalidOperationException:LINQ表达式'DbSet.where(p => __filterTags_0.Any(tag => p.Tags.Contains(tag)))'无法翻译.以一种可以翻译的形式重写查询,或者通过插入对AsEnumerable(),AsAsyncEnumerable(),ToList()或ToListAsync()的调用来显式切换到客户端评估

System.InvalidOperationException: The LINQ expression 'DbSet .Where(p => __filterTags_0 .Any(tag => p.Tags.Contains(tag)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

有人知道这是什么意思还是我做错了什么?

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查找文本字段是否在列表中包含任何字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆