2015-06-20 42 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"); 
相关问题