我对此做了一点研究,并在StackOverflow以及一些博客文章中查看了一些文章,但还没有找到确切的答案。我还读到可以使用4.0框架来完成,但还没有找到任何支持证据。LINQ to SQL SOUNDEX - 可能吗?
所以我的问题是否可以通过LINQ to SQL Query执行SOUNDEX?
我对此做了一点研究,并在StackOverflow以及一些博客文章中查看了一些文章,但还没有找到确切的答案。我还读到可以使用4.0框架来完成,但还没有找到任何支持证据。LINQ to SQL SOUNDEX - 可能吗?
所以我的问题是否可以通过LINQ to SQL Query执行SOUNDEX?
您可以通过使用伪UDF在数据库中执行此操作;在部分类,一个方法添加到数据上下文:
x => db.SoundsLike(x.QuoteValue) == db.SoundsLike("text")
初始想法来自: Random row from Linq to Sql
这恰恰是Troy Magennis在“LINQ to Objects Using C# 4.0”中演示的东西。
编辑:添加示例tid位和澄清:作者的例子是LINQ到对象,而不是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());
对于那些没有这本书的人,你有一个例子吗? – 2010-06-07 21:01:10
虽然我感谢你对Mystagogue的回应,但是一个例子或者一个例子的链接比我可以购买的一本书的链接更有用。 – 2010-06-07 21:16:19
在SQL Server中,你可以在一个UDF(用户定义函数)包装SOUNDEX。您可以将它添加到您的DataContext类中,然后您应该可以通过DataContext使用它。
你能提供一个这样的例子吗? – 2010-06-07 21:17:33
添加UDF如下
CREATE FUNCTION [dbo].[udfSoundex]
(
@Soundex nvarchar(100)
)
RETURNS nvarchar(100)
AS
BEGIN
RETURN Soundex(@Soundex)
END
只需从服务器资源管理器在Visual Studio DBML文件拖放到你的数据上下文和代码暴露在你的DataContext类的方法使用它..
由于.NET 4此
[DbFunction(Name = "SoundEx", IsComposable = true)]
public string SoundsLike(string input)
{
throw new NotImplementedException();
}
可以像表达式中使用也可以工作:
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
您还可以使用SqlFucntions.Difference方法,它映射到了Soundex功能:
SqlFunctions.Difference(字符串,字符串)返回int - 更高的返回值,更多的“相似”的字符串是。
这是EF,而不是Linq To SQL。 – 2016-03-29 15:18:40
对于那些试图与新版本:(以及为我自己的未来参考)[DbFunction(“SqlServer”,“SOUNDEX”)] – 2015-07-06 18:02:36