c# - 如何在 Dictionary<string, int> 中通过不区分大小写的键获取原始大小写键

标签 c# dictionary case-insensitive

有字典:

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/

相关文章:

c# - 基于输入的动态返回类型 - asp.net

c# - 如何在 C# 上使对象线程安全?

Python - 如何在字典中搜索特定字符串?

Python (DICT) - 用 JSON 填充 - 无法在请求中使用变量

javascript - 从多边形的中心(多边形)边界内生成 n 个随机点(Lat Lng 对)

MySQL:小写或大写正则表达式安全吗?

LINQ to DataSet 不区分大小写的分组依据

c# - 连接表,获取对象引用未设置

kotlin - 区分大小写 Kotlin/ignoreCase

c# - 如何禁用 Windows 平板电脑内置的网络摄像头