[英]How to do a string compare using regex and linq to sql
以下代码因错误而失败:
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;
}
没有创建自定义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
只需使用兼容的like语句替换函数中的模式:
'%[^A-Za-z0-9.,]%'
您可以从LINQ到SQL调用用户定义的函数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.