2013-04-30 52 views
1

我想更改字典的键值的格式。格式化字典的键值

喜欢的东西

Dictionary<string,string> dictcatalogue = new Dictionary<string,string>(); 

dictCatalogue = dictCatalogue.Select(t => t.Key.ToString().ToLower() + "-ns").ToDictionary(); 

我怎样才能改变我的字典的关键,而不会影响值

回答

5

你是在正确的轨道上建立一个新的字典:

dictcatalogue = dictcatalogue.ToDictionary 
     (t => t.Key.ToString().ToLower() + "-ns", t => t.Value); 
+1

这个工作,但它会创建一个新的对象(字典)对于大型字典可以抛出内存溢出异常 – 2013-04-30 11:47:43

0

您不能更改现有的字典条目的关键。您必须使用新密钥进行删除/添加。

你需要做什么?或许我们可以提出一个更好的办法来做到这一点

0

我鼓励你考虑stuartd的answer为合适的解决方案。不过,如果你有兴趣的方式通过忽略大小写,而不是创建一个新的字典与词典的工作,看看下面的代码片段:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var searchedTerm = "test2-ns"; 
     Dictionary<string, string> dictCatalogue = 
      new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); 
     dictCatalogue.Add("test1", "value1"); 
     dictCatalogue.Add("Test2", "value2"); 

     // looking for the key with removed "-ns" suffix 
     var value = dictCatalogue[searchedTerm 
      .Substring(0, searchedTerm.Length - 3)]; 

     Console.WriteLine(value); 
    } 
} 

// Output 
value2