有字典:
var dictionary1 = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{{"abc1", 1}, {"abC2", 2}, {"abc3", 3}};
我可以得到一个值:
var value = dictionary1["Abc2"];
如果搜索键 "Abc2"
我需要得到原始键 "abC2"
和值 2。
如何通过不区分大小写的 key 获取原始大小写 key ?
最佳答案
不幸的是,你不能那样做。 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
}
如果这是类中的一个字段,您可以编写辅助方法以使其更简单。您甚至可以围绕 Dictionary
编写自己的包装类实现IDictionary<TKey, TValue>
但添加一个额外的 TryGetEntry
方法,因此调用者永远不需要知道“内部”字典是什么样子。
关于c# - 如何在 Dictionary<string, int> 中通过不区分大小写的键获取原始大小写键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52325784/