2015-06-20 68 views
-1

我工作的SQL CLR應用程序,添加了與SQL整合後,我收到此錯誤(英文它的工作,但問題的同時,將統一碼到dictionory):一個具有相同的鍵項目已經在字典

**Msg 6522, Level 16, State 2, Line 1 
A .NET Framework error occurred during execution of user-defined routine or  aggregate "SqlCompare": 
System.ArgumentException: An item with the same key has already been added. 
System.ArgumentException: 
    at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) 
    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value,  Boolean add) 
    at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) 
    at Translate_Class_NUM..ctor() 
    at StringPercentageCompare..ctor() 
    at UserDefinedFunctions.SqlComparison()** 

here is my code in c# 
private Dictionary<string, string> MyDictionary; 
//private string[,] MyArray; 

public Translate_Class_NUM() 
{ 
    MyDictionary.Add("?", "01"); 
    MyDictionary.Add("?", "02"); 
    MyDictionary.Add("?", "03"); 
    MyDictionary.Add("?", "04"); 
    MyDictionary.Add("?", "05") 
} 

和SQL Server代碼是 從CREATE ASSEMBLY DBDB_DeDuplication AUTHORIZATION DBO 'E:\項目\ DBDB_DeDuplication \ DBDB_DeDuplication \ OBJ \調試\ DBDB_DeDuplication.dll' WITH PERMISSION_SET = SAFE GO

CREATE FUNCTION SqlCompare()RETURNS nvarchar(50) AS EXTERNAL NAME DBDB_DeDuplication.UserDefinedFunctions.SqlComparison; GO

SELECT dbo.SqlCompare(); GO提前

感謝

+0

您不能將多個值添加到同一個鍵。 'MyDictionary.Add(「?」,「01」);'在鍵「'?」下放置值字符串「01」,接下來的行會失敗,因爲它使用相同的鍵「」?「'。你可以使用'MyDictionary [「?」] =「01」'語法來代替它,它不會出錯,但是你會覆蓋你之前的值。你的字典用法有問題 - 你是否改變了你的值和鍵? –

+0

S瞭解...?在unicode的意義上不同的字符..這裏顯示爲?只有..但在代碼中我使用不同的Unicode字符 – Santhosh

+0

S.它正在爲dictionary.add(「a」,「01」)dictionary.add(「b」,「02」)工作,但不適用於unicode字符... dictionary.add(「ಅ」,「01」)dictionary.add(「ಇ」,「02」) – Santhosh

回答

2

此代碼工作對我蠻好:

Dictionary<string, string> dict = new Dictionary<string, string>(); 
dict.Add("ಅ","01"); 
dict.Add("ಇ","02"); 

正如我試圖在評論前解釋,你的Unicode字符串必須不通過傳遞到編譯器你期望的方式。有時這可能是由於C#源文件使用ASCII編碼或其他非Unicode支持編碼進行保存。要保證結果,請使用C#Unicode文字編碼(U + 0000到U + FFFF)。

如果你不知道如何獲得等價的Unicode轉義序列,您可以使用此代碼:

static string EncodeNonAsciiCharacters(string value) 
{ 
    StringBuilder sb = new StringBuilder(); 
    foreach(char c in value) { 
     if(c > 127) { 
      // This character is too big for ASCII 
      string encodedValue = "\\u" + ((int) c).ToString("x4"); 
      sb.Append(encodedValue); 
     } 
     else { 
      sb.Append(c); 
     } 
    } 
    return sb.ToString(); 
} 

Console.WriteLine(EncodeNonAsciiCharacters("ಅ")); 
\u0c85 
Console.WriteLine(EncodeNonAsciiCharacters("ಇ")); 
\u0c87 

,那麼你可以寫安全版本的源代碼爲:

Dictionary<string, string> dict = new Dictionary<string, string>(); 
dict.Add("\u0c85","01"); 
dict.Add("\u0c87","02"); 
相關問題