如何在Dictionary <string,int>中通过大小写不敏感的密钥获取原始大小写密钥

ild*_*dar 2 c# dictionary case-insensitive

有词典:

var dictionary1 = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
    {{"abc1", 1}, {"abC2", 2}, {"abc3", 3}};
Run Code Online (Sandbox Code Playgroud)

我可以得到一个值:

var value = dictionary1["Abc2"];
Run Code Online (Sandbox Code Playgroud)

如果搜索键"Abc2"我需要获取原始键"abC2"和值2.

如何通过不区分大小写的密钥获取原始案例密钥?

Jon*_*eet 5

不幸的是,你不能这样做.Dictionary<TKey, TValue>公开bool TryGetEntry(TKey key, KeyValuePair<TKey, TValue> entry)方法是完全合理的,但它没有这样做.

正如评论中提出的stop-cran一样,最简单的方法可能是使字典中的每个与字典中的键具有相同的键.所以:

var dictionary = new Dictionary<string, KeyValuePair<string, int>>(StringComparer.OrdinalIgnoreCase)
{
    // You'd normally write a helper method to avoid having to specify
    // the key twice, of course.
    {"abc1", new KeyValuePair<string, int>("abc1", 1)},
    {"abC2", new KeyValuePair<string, int>("abC2", 2)},
    {"abc3", new KeyValuePair<string, int>("abc3", 3)}
};
if (dictionary.TryGetValue("Abc2", out var entry))
{
    Console.WriteLine(entry.Key); // abC2
    Console.WriteLine(entry.Value); // 2
}
else
{
    Console.WriteLine("Key not found"); // We don't get here in this example
}
Run Code Online (Sandbox Code Playgroud)

如果这是类中的字段,则可以编写辅助方法以使其更简单.您甚至可以编写自己的包装类Dictionary来实现,IDictionary<TKey, TValue>但添加一个额外的TryGetEntry方法,以便调用者永远不需要知道"内部"字典是什么样的.