LINQ to Objects中的Like运算符

12

我正在尝试在LINQ to Objects中模拟LIKE运算符。

这是我的代码:

List<string> list = new List<string>();
list.Add("line one");
list.Add("line two");
list.Add("line three");
list.Add("line four");
list.Add("line five");
list.Add("line six");
list.Add("line seven");
list.Add("line eight");
list.Add("line nine");
list.Add("line ten");

string pattern = "%ine%e";

var res = from i in list
            where System.Data.Linq.SqlClient.SqlMethods.Like(i, pattern)
              select i;

因为System.Data.Linq.SqlClient.SqlMethods.Like只用于翻译成SQL,所以它没有给我带来结果。

在LINQ to Objects的世界中是否存在类似于sql LIKE运算符的东西?

5个回答

18

我不知道是否存在现成的工具,但是如果你熟悉正则表达式,你可以自己编写:

using System;
using System.Text.RegularExpressions;

public static class MyExtensions
{
    public static bool Like(this string s, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
    {
        return Regex.IsMatch(s, pattern, options);
    }
}

然后在你的代码中:

string pattern = ".*ine.*e";
var res = from i in list
    where i.Like(pattern)
    select i;

哇!这是比其他答案更棒的回答!非常感谢你。 - Anton Semenov

8

这段代码将模拟Sql LIKE的行为和语法。您可以将它包装成自己的lambda或扩展方法,以在Linq语句中使用:

public static bool IsSqlLikeMatch(string input, string pattern)
{
   /* Turn "off" all regular expression related syntax in
    * the pattern string. */
   pattern = Regex.Escape(pattern);

   /* Replace the SQL LIKE wildcard metacharacters with the
    * equivalent regular expression metacharacters. */
   pattern = pattern.Replace("%", ".*?").Replace("_", ".");

   /* The previous call to Regex.Escape actually turned off
    * too many metacharacters, i.e. those which are recognized by
    * both the regular expression engine and the SQL LIKE
    * statement ([...] and [^...]). Those metacharacters have
    * to be manually unescaped here. */
   pattern = pattern.Replace(@"\[", "[").Replace(@"\]", "]").Replace(@"\^", "^");

   return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
}

一个草率地拼凑而成的扩展方法,可以像 IEnumerable<T>.Where 方法一样工作:
public static IEnumerable<T> Like<T>(this IEnumerable<T> source, Func<T, string> selector, string pattern)
{
   return source.Where(t => IsSqlLikeMatch(selector(t), pattern));
}

这将使您能够像这样格式化您的语句:
string pattern = "%ine%e";
var res = list.Like(s => s, pattern);

编辑 如果有人想使用这个代码,可以采用改进后的实现。它只需要将正则表达式转换和编译一次,而不是为每个项都进行一次转换。上面从LIKE到正则表达式的转换存在一些错误。

public static class LikeExtension
{
    public static IEnumerable<T> Like<T>(this IEnumerable<T> source, Func<T, string> selector, string pattern)
    {
        var regex = new Regex(ConvertLikeToRegex(pattern), RegexOptions.IgnoreCase);
        return source.Where(t => IsRegexMatch(selector(t), regex));
    }

    static bool IsRegexMatch(string input, Regex regex)
    {
        if (input == null)
            return false;

        return regex.IsMatch(input);
    }

    static string ConvertLikeToRegex(string pattern)
    {
        StringBuilder builder = new StringBuilder();
        // Turn "off" all regular expression related syntax in the pattern string
        // and add regex begining of and end of line tokens so '%abc' and 'abc%' work as expected
        builder.Append("^").Append(Regex.Escape(pattern)).Append("$");

        /* Replace the SQL LIKE wildcard metacharacters with the
        * equivalent regular expression metacharacters. */
        builder.Replace("%", ".*").Replace("_", ".");

        /* The previous call to Regex.Escape actually turned off
        * too many metacharacters, i.e. those which are recognized by
        * both the regular expression engine and the SQL LIKE
        * statement ([...] and [^...]). Those metacharacters have
        * to be manually unescaped here. */
        builder.Replace(@"\[", "[").Replace(@"\]", "]").Replace(@"\^", "^");

        // put SQL LIKE wildcard literals back
        builder.Replace("[.*]", "[%]").Replace("[.]", "[_]");

        return builder.ToString();
    }
}

1
我应该指出,我个人不能为IsSqlLikeMatch的实现负责。几年前在互联网上找到它。我能找到的最好的归属是:http://bytes.com/topic/c-sharp/answers/253519-using-regex-create-sqls-like-like-function 我认为那是原始来源。 - dkackman

5

您需要使用正则表达式(Regex)来匹配模式,然后使用扩展方法Where进行迭代并查找匹配项。

因此,您的代码应该如下所示:

string pattern = @".*ine.*e$";

var res = list.Where( e => Regex.IsMatch( e, pattern));

如果您对正则表达式不熟悉,这里是解释:

首先是 0 或多个任意字符 (.*),接着是 ine (ine),然后是 0 或多个任意字符 (.*),最后是并列的 e (e),且 e 必须是字符串的结尾 ($)


1

1. 使用 String.StartsWith 或 String.Endswith

编写以下查询:

var query = from c in ctx.Customers

            where c.City.StartsWith("Lo")

            select c;

will generate this SQL statement:
SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [Lo%]

这正是我们想要的。String.EndsWith也是如此。

但是,如果我们想查询城市名称为“L_n%”的客户呢?(以大写字母'L'开头,然后是一些字符,然后是'n',最后是名称的其余部分)。使用以下查询:

var query = from c in ctx.Customers

            where c.City.StartsWith("L") && c.City.Contains("n")

            select c;

generates the statement:
SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [L%]
AND      City LIKE [%n%]

这并不完全是我们想要的,而且也更加复杂。

2. 使用 SqlMethods.Like 方法

深入研究 System.Data.Linq.SqlClient 命名空间,我发现了一个叫做 SqlMethods 的小助手类,它在这种情况下非常有用。SqlMethods 有一个叫做 Like 的方法,可以在 Linq to SQL 查询中使用:

var query = from c in ctx.Customers

            where SqlMethods.Like(c.City, "L_n%")

            select c;

此方法获取要检查的字符串表达式(例如客户所在的城市),以及要针对其进行测试的模式,就像在SQL中编写LIKE子句一样提供。

使用上述查询生成了所需的SQL语句:

SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [L_n%]

来源: http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx


1
谢谢您的回答!但是您说的是什么?不幸的是,我们无法在LINQ to objects中使用SqlMethods.Like,正如我在问题中提到的那样。 - Anton Semenov

0

我不知道它是否存在,但这里是我使用Knuth-Morris-Pratt算法实现的扩展方法。

public static IEnumerable<T> Like<T>(this IEnumerable<T> lista, Func<T, string> type, string pattern)
            {

                int[] pf = prefixFunction(pattern);

                foreach (T e in lista)
                {
                    if (patternKMP(pattern, type(e), pf))
                        yield return e;
                }

            }

            private static int[] prefixFunction(string p)
            {


                int[] pf = new int[p.Length];
                int k = pf[0] = -1;


                for (int i = 1; i < p.Length; i++)
                {
                    while (k > -1 && p[k + 1] != p[i])
                        k = pf[k];

                    pf[i] = (p[k + 1] == p[i]) ? ++k : k;
                }
                return pf;

            }

            private static bool patternKMP(string p, string t, int[] pf)
            {

                for (int i = 0, k = -1; i < t.Length; i++)
                {

                    while (k > -1 && p[k + 1] != t[i])
                        k = pf[k];

                    if (p[k + 1] == t[i])
                        k++;

                    if (k == p.Length - 1)
                        return true;    
                }

                return false;

            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接