C# 格式化字典的键值

C# 格式化字典的键值,c#,dictionary,C#,Dictionary,我想更改字典键值的格式 差不多 Dictionary<string,string> dictcatalogue = new Dictionary<string,string>(); dictCatalogue = dictCatalogue.Select(t => t.Key.ToString().ToLower() + "-ns").ToDictionary(); 字典目录=新字典(); dictcatalog=dictcatalog.Select(t=>t.

我想更改字典键值的格式

差不多

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

dictCatalogue = dictCatalogue.Select(t => t.Key.ToString().ToLower() + "-ns").ToDictionary();
字典目录=新字典();
dictcatalog=dictcatalog.Select(t=>t.Key.ToString().ToLower()+“-ns”).ToDictionary();

如何在不影响值的情况下更改词典的键

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


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

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


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

创建新词典的方法是正确的:

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

创建新词典的方法是正确的:

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

我鼓励你认为斯图亚特是正确的解决方案。尽管如此,如果您对通过忽略大小写敏感度而不创建新字典来使用字典感兴趣,请查看以下代码段:

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
类程序
{
静态void Main(字符串[]参数)
{
var searchedTerm=“test2 ns”;
字典目录=
新字典(StringComparer.InvariantCultureInogoreCase);
添加(“测试1”、“价值1”);
添加(“测试2”、“价值2”);
//正在查找带有已删除“-ns”后缀的密钥
var值=目录[searchedTerm]
.子字符串(0,搜索项长度-3)];
控制台写入线(值);
}
}
//输出
价值2

我鼓励你考虑斯图亚特是正确的解决方案。尽管如此,如果您对通过忽略大小写敏感度而不创建新字典来使用字典感兴趣,请查看以下代码段:

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
类程序
{
静态void Main(字符串[]参数)
{
var searchedTerm=“test2 ns”;
字典目录=
新字典(StringComparer.InvariantCultureInogoreCase);
添加(“测试1”、“价值1”);
添加(“测试2”、“价值2”);
//正在查找带有已删除“-ns”后缀的密钥
var值=目录[searchedTerm]
.子字符串(0,搜索项长度-3)];
控制台写入线(值);
}
}
//输出
价值2

这可以工作,但它会创建一个新对象(字典)。对于大型字典,它会引发内存溢出异常。对于大型字典,它可以工作,但它会创建一个新对象(字典)。对于大型字典,它会引发内存溢出异常