Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
LINQ to SQL-选择类似文本的字符串数组的位置_Sql_Linq_Linq To Sql_Sql Like - Fatal编程技术网

LINQ to SQL-选择类似文本的字符串数组的位置

LINQ to SQL-选择类似文本的字符串数组的位置,sql,linq,linq-to-sql,sql-like,Sql,Linq,Linq To Sql,Sql Like,我有一个变量count的列表,我想(通过LINQ)查询一个表,以查找文本列中包含这些字符串的任何项 尝试了以下操作(无效): 查询类似于: select * from items where text like '%string1%' or text like '%string2%' 这可能吗?对于整个LINQ-to-SQL游戏来说有点陌生,但是这种语法有帮助吗 string[] items = new string[] { "a", "b", "c", "d" }; var items =

我有一个变量count的列表
,我想(通过LINQ)查询一个表,以查找文本列中包含这些字符串的任何项

尝试了以下操作(无效):

查询类似于:

select * from items where text like '%string1%' or text like '%string2%'

这可能吗?

对于整个LINQ-to-SQL游戏来说有点陌生,但是这种语法有帮助吗

string[] items = new string[] { "a", "b", "c", "d" };

var items = from i in db.Items
             where items.Contains(p.text)
            select i;
从以下方面获得:


查看这篇文章,做你想做的事:


这就像一场梦。我基本上剪切并粘贴了他们的代码,并将其恢复(当然是使用我自己的数据方案):

以下是我为概念验证而运行的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace PredicateTest
{
class Program
{
    static void Main(string[] args)
    {
        DataClasses1DataContext dataContext = new DataClasses1DataContext();

        Program p = new Program();
        Program.SearchCompanies("test", "test2");
        var pr = from pi in  dataContext.Companies.Where(Program.SearchCompanies("test", "test2")) select pi;
    }

    DataClasses1DataContext dataContext = new DataClasses1DataContext();

    public static Expression<Func<Company, bool>> SearchCompanies(
                                                  params string[] keywords)
    {
        var predicate = PredicateBuilder.False<Company>();
        foreach (string keyword in keywords)
        {
            string temp = keyword;
            predicate = predicate.Or(p => p.Name.Contains(temp));
        }
        return predicate;
    }

}

public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                         Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Linq.Expressions;
命名空间谓词测试
{
班级计划
{
静态void Main(字符串[]参数)
{
DataClasses1DataContext dataContext=新DataClasses1DataContext();
程序p=新程序();
搜索公司(“测试”、“测试2”);
var pr=来自dataContext.companys.Where(Program.searchcompanys(“test”、“test2”))中的pi选择pi;
}
DataClasses1DataContext dataContext=新DataClasses1DataContext();
上市公司(
参数字符串[]关键字)
{
var predicate=PredicateBuilder.False();
foreach(关键字中的字符串关键字)
{
字符串temp=关键字;
谓词=谓词。或(p=>p.Name.Contains(temp));
}
返回谓词;
}
}
公共静态类谓词生成器
{
公共静态表达式True(){return f=>True;}
公共静态表达式False(){return f=>False;}
公共静态表达式或(此表达式expr1,
表达式expr2)
{
var invokedExpr=Expression.Invoke(expr2,expr1.Parameters.Cast());
返回表达式.Lambda
(Expression.OrElse(expr1.Body,invokedExpr),expr1.Parameters);
}
公共静态表达式和(此表达式expr1,
表达式expr2)
{
var invokedExpr=Expression.Invoke(expr2,expr1.Parameters.Cast());
返回表达式.Lambda
(Expression.AndAlso(expr1.Body,invokedExpr),expr1.Parameters);
}
}
}
我建议去网站上了解代码和解释


(我留下第一个答案,因为如果您需要IN语句,它可以很好地工作)

在阅读这篇文章,寻找与您相同的解决方案后,我找到了一个使用
。Any
的解决方案。Linq的所有
方法都是获得阵列匹配结果的简单而优雅的好方法

在本例中,我使用一个搜索输入,以逗号分隔作为示例。我不在乎比赛是否在同一个情况下

var qry = Query.Split(',').Select(c => c.Trim().ToLower());
首先获取一些要查询的数据,从Linq到SQL或其他任何地方

var search = db.tablename;
将lambda语法用于紧凑的代码,并将查询中的任何
字符串与表中的名称或描述进行匹配

search = search.Where(
    record => 
    qry.Any(q => record.Name.ToLower().Contains(q)) || 
    qry.Any(q => record.Description.ToLower().Contains(q)));
如果只希望在任何字段中匹配所有字符串的结果,则可以将
.any
替换为
.all

search = search.Where(
    record => 
    qry.All(q => record.Name.ToLower().Contains(q)) || 
    qry.All(q => record.Description.ToLower().Contains(q)));

使用:

string searh = "test1 test2,test3";    
data.Persons.Search(p => p.Name, search);
public static IQueryable<T> Search<T>(this IQueryable<T> source, Expression<Func<T, string>> selector, string s)
{
    if (string.IsNullOrEmpty(s))
        return source;

    string[] str = s.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);

    MethodInfo methodContains = typeof(string).GetMethod("Contains", new[] { typeof(string) });

    Expression strExpression;
    Expression expressionContains;
    Expression resultExpression = Expression.Empty();

    for (int i = 0; i < str.Length; i++)
    {
        strExpression = Expression.Constant(str[i].Trim(), typeof(string));
        expressionContains = Expression.Call(selector.Body, methodContains, strExpression);

        if (i == 0)
            resultExpression = expressionContains;
        else
            resultExpression = Expression.OrElse(resultExpression, expressionContains);
    }

    Expression<Func<T, bool>> lambdaExpr = Expression.Lambda<Func<T, bool>>(resultExpression, new ParameterExpression[] { selector.Parameters[0] });

    return source.Where(lambdaExpr);
}
搜索功能是:

string searh = "test1 test2,test3";    
data.Persons.Search(p => p.Name, search);
public static IQueryable<T> Search<T>(this IQueryable<T> source, Expression<Func<T, string>> selector, string s)
{
    if (string.IsNullOrEmpty(s))
        return source;

    string[] str = s.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);

    MethodInfo methodContains = typeof(string).GetMethod("Contains", new[] { typeof(string) });

    Expression strExpression;
    Expression expressionContains;
    Expression resultExpression = Expression.Empty();

    for (int i = 0; i < str.Length; i++)
    {
        strExpression = Expression.Constant(str[i].Trim(), typeof(string));
        expressionContains = Expression.Call(selector.Body, methodContains, strExpression);

        if (i == 0)
            resultExpression = expressionContains;
        else
            resultExpression = Expression.OrElse(resultExpression, expressionContains);
    }

    Expression<Func<T, bool>> lambdaExpr = Expression.Lambda<Func<T, bool>>(resultExpression, new ParameterExpression[] { selector.Parameters[0] });

    return source.Where(lambdaExpr);
}
公共静态IQueryable搜索(此IQueryable源、表达式选择器、字符串s)
{
if(string.IsNullOrEmpty)
返回源;
string[]str=s.Split(新字符[]{'',','},StringSplitOptions.RemoveEmptyEntries);
MethodInfo methodContains=typeof(string).GetMethod(“Contains”,new[]{typeof(string)});
表达谱;
表达包含;
表达式resultExpression=Expression.Empty();
对于(int i=0;i
感谢Matthew的想法,但这会生成以下SQL:从[dbo].[Table]中选择[t0].[Text]作为[t0],其中[t0].[Text]在(@p0)中,它在数组的每个项中查找文本列,而不是在文本列中查找数组的每个项。