我对此进行了一些研究,并浏览了 StackOverflow 上的一些文章以及一些博客文章,但还没有找到确切的答案。我还读到使用 4.0 框架可以做到这一点,但还没有找到任何支持证据。
所以我的问题是,是否可以通过 LINQ to SQL 查询执行 SOUNDEX?
我对此进行了一些研究,并浏览了 StackOverflow 上的一些文章以及一些博客文章,但还没有找到确切的答案。我还读到使用 4.0 框架可以做到这一点,但还没有找到任何支持证据。
所以我的问题是,是否可以通过 LINQ to SQL 查询执行 SOUNDEX?
您可以在数据库中使用伪造的 UDF 来执行此操作;在部分类中,向数据上下文添加一个方法:
[DbFunction(Name = "SoundEx", IsComposable = true)]
public string SoundsLike(string input)
{
throw new NotImplementedException();
}
您可以使用如下表达式:
x => db.SoundsLike(x.QuoteValue) == db.SoundsLike("text")
最初的想法来自: 从 Linq 到 Sql 的随机行
如下添加一个udf
CREATE FUNCTION [dbo].[udfSoundex]
(
@Soundex nvarchar(100)
)
RETURNS nvarchar(100)
AS
BEGIN
RETURN Soundex(@Soundex)
END
只需将它从服务器资源管理器拖到 Visual Studio dbml 文件中的数据上下文中,然后在代码中将其用作数据上下文类中公开的方法。
从 .net 4 开始,这也可以:
from p in mytable
where SqlFunctions.SoundCode(p.MyRow) == SqlFunctions.SoundCode("test")
select p
更多信息在这里:http: //msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.soundcode.aspx
这正是Troy Magennis在“使用 C# 4.0 的 LINQ to Objects ”中演示的内容。
编辑:添加示例花絮和说明:作者的示例是针对 LINQ to 对象而不是 LINQ to SQL。作者简单地做了一个IEqualityComparer,其中一些看起来像这样......
public class SoundexEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return GetHashCode(x) == GetHashCode(y);
}
public int GetHashCode(string obj)
{
//e.g. convert soundex code A123,
//to an integer: 65123
int result = 0;
string s = soundex(obj);
if (string.IsNullOrEmpty(s) == false)
result = Convert.ToInt32(s[0]) * 1000 +
Convert.ToInt32(s.Substring(1, 3));
return result;
}
private string soundex(string s)
{
//e.g. book's implementation omitted for this post.
}
}
//example usage (assuming an array of strings in "names")
var q = names.GroupBy(s => s, new SoundexEqualityComparer() );
在 SQL Server 上,您可以将 SOUNDEX 包装在 UDF(用户定义函数)中。您可以将它添加到您的 DataContext 类中,然后您应该能够通过 DataContext 使用它。
您还可以使用映射到 Soundex 函数的 SqlFucntions.Difference 方法:
SqlFunctions.Difference(string, string) 返回 int - 返回值越高,字符串越“相似”。