简体   繁体   中英

How to do a string compare using regex and linq to sql

The code below fails with error:

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.

I understand that my CompareNames method cannot be converted to a SQL statement but want to know a way to accomplish this task without pulling the entire table from the database to compare.

// 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;
}

There is no easy way without creating a custom SQL function. This function gives you a pretty decent starting point:

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/

Just replace the pattern in the function with a compatible like statement:

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

You can call a user defined function from LINQ to SQL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM