如何使用正则表达式和linq到sql进行字符串比较

时间:2017-09-23 15:12:45

标签: c# linq

以下代码失败,错误:

LINQ to Entities does not recognize the method 'Boolean CompareNames(System.String, System.String)' method, and this method cannot be translated into a store expression.

我知道我的CompareNames方法无法转换为SQL语句,但想要知道一种方法来完成此任务,而无需从数据库中提取整个表进行比较。

// Use my method in Linq to Sql lambda
Repo.Get<T>(c => CompareNames(c.Name, newName)).ToList()

// Compare two names removing spaces and non-numeric characters
private static bool CompareNames(string str1, string str2)
{
    str1 = Regex.Replace(str1.Trim(), "[^a-z,A-Z,0-9.]", "");
    str2 = Regex.Replace(str2.Trim(), "[^a-z,A-Z,0-9.]", "");

    return str1 == str2;
}

1 个答案:

答案 0 :(得分:4)

没有创建自定义SQL函数就没有简单的方法。这个函数为你提供了一个相当不错的起点:

CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
    DECLARE @intAlpha INT
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
    BEGIN
        WHILE @intAlpha > 0
        BEGIN
            SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
            SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
        END
    END
    RETURN ISNULL(@strAlphaNumeric,0)
END
GO

https://blog.sqlauthority.com/2008/10/14/sql-server-get-numeric-value-from-alpha-numeric-string-udf-for-get-numeric-numbers-only/

只需用兼容的like语句替换函数中的模式:

'%[^A-Za-z0-9.,]%'

你可以call a user defined function from LINQ to SQL