格式化字典的键值

本文关键字:键值 字典 格式化 | 更新日期: 2023-09-27 18:11:35

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

之类的
Dictionary<string,string> dictcatalogue = new Dictionary<string,string>();
dictCatalogue = dictCatalogue.Select(t => t.Key.ToString().ToLower() + "-ns").ToDictionary();

如何在不影响值

格式化字典的键值

的情况下改变字典的键呢?

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

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

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

你需要做什么?也许我们可以建议一个更好的方法

我鼓励您考虑stuart的答案是正确的解决方案。但是,如果您对忽略大小写敏感性而不创建新字典的方法感兴趣,请查看以下代码片段:

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