2010-06-07 63 views
10

我對此做了一點研究,並在StackOverflow以及一些博客文章中查看了一些文章,但還沒有找到確切的答案。我還讀到可以使用4.0框架來完成,但還沒有找到任何支持證據。LINQ to SQL SOUNDEX - 可能嗎?

所以我的問題是否可以通過LINQ to SQL Query執行SOUNDEX?

回答

20

您可以通過使用僞UDF在數據庫中執行此操作;在部分類,一個方法添加到數據上下文:

x => db.SoundsLike(x.QuoteValue) == db.SoundsLike("text") 

初始想法來自: Random row from Linq to Sql

+2

對於那些試圖與新版本:(以及爲我自己的未來參考)[DbFunction(「SqlServer」,「SOUNDEX」)] – 2015-07-06 18:02:36

2

這恰恰是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()); 
+4

對於那些沒有這本書的人,你有一個例子嗎? – 2010-06-07 21:01:10

+2

雖然我感謝你對Mystagogue的迴應,但是一個例子或者一個例子的鏈接比我可以購買的一本書的鏈接更有用。 – 2010-06-07 21:16:19

0

在SQL Server中,你可以在一個UDF(用戶定義函數)包裝SOUNDEX。您可以將它添加到您的DataContext類中,然後您應該可以通過DataContext使用它。

+0

你能提供一個這樣的例子嗎? – 2010-06-07 21:17:33

5

添加UDF如下

CREATE FUNCTION [dbo].[udfSoundex] 
(
    @Soundex nvarchar(100) 
) 
RETURNS nvarchar(100) 
AS 
BEGIN 
    RETURN Soundex(@Soundex) 
END 

只需從服務器資源管理器在Visual Studio DBML文件拖放到你的數據上下文和代碼暴露在你的DataContext類的方法使用它..

4

由於.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

+1

這似乎是一個實體框架和NOT LINQ到SQL的參考,這解釋了爲什麼沒有上票。 – jpierson 2013-06-04 22:29:41

+0

@jpierson真的,我的壞。但我發現這個問題尋找一個EF解決方案,所以也許它會幫助別人。 – Marthijn 2013-06-07 09:11:14

0

您還可以使用SqlFucntions.Difference方法,它映射到了Soundex功能:

SqlFunctions.Difference(字符串,字符串)返回int - 更高的返回值,更多的「相似」的字符串是。

+0

這是EF,而不是Linq To SQL。 – 2016-03-29 15:18:40