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

有字典:


var dictionary1 = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)

    {{"abc1", 1}, {"abC2", 2}, {"abc3", 3}};

我可以得到一个值:


var value = dictionary1["Abc2"];

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


如何通过不区分大小写的键获取原始大小写键?


缥缈止盈
浏览 247回答 2
2回答

慕田峪4524236

不幸的是,你不能这样做。Dictionary<TKey, TValue>公开一个方法是完全合理的bool TryGetEntry(TKey key, KeyValuePair<TKey, TValue> entry),但它并没有这样做。正如评论中所建议的那样,最简单的方法可能是使字典中的每个值都具有与字典中的键相同的键。所以:var dictionary = new Dictionary<string, KeyValuePair<string, int>>(StringComparer.OrdinalIgnoreCase){&nbsp; &nbsp; // You'd normally write a helper method to avoid having to specify&nbsp; &nbsp; // the key twice, of course.&nbsp; &nbsp; {"abc1", new KeyValuePair<string, int>("abc1", 1)},&nbsp; &nbsp; {"abC2", new KeyValuePair<string, int>("abC2", 2)},&nbsp; &nbsp; {"abc3", new KeyValuePair<string, int>("abc3", 3)}};if (dictionary.TryGetValue("Abc2", out var entry)){&nbsp; &nbsp; Console.WriteLine(entry.Key); // abC2&nbsp; &nbsp; Console.WriteLine(entry.Value); // 2}else{&nbsp; &nbsp; Console.WriteLine("Key not found"); // We don't get here in this example}如果这是类中的一个字段,您可以编写辅助方法以使其更简单。您甚至可以编写自己的包装类Dictionary来实现IDictionary<TKey, TValue>但添加一个额外的TryGetEntry方法,以便调用者永远不需要知道“内部”字典的样子。

冉冉说

即使大小写与键不匹配,您也可以使用以下利用 LINQ 的代码来获取字典键值对。注意:此代码可用于任何大小的字典,但它最适合较小大小的字典,因为 LINQ 基本上是一一检查每个键值对,而不是直接转到所需的键值对。Dictionary<string,int> dictionary1 = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase){&nbsp; &nbsp; {"abc1",1},&nbsp; &nbsp; {"abC2",2},&nbsp; &nbsp; {"abc3",3}&nbsp; &nbsp; } ;var value1 = dictionary1["ABC2"];//this gives 2, even though case of key does not macth//use LINQ to achieve your requirementvar keyValuePair1 = dictionary1.SingleOrDefault (d => d.Key.Equals("Abc2", StringComparison.OrdinalIgnoreCase) );var key1 = keyValuePair1.Key ;//gives us abC2var value2 =keyValuePair1.Value;//gives us 2
打开App,查看更多内容
随时随地看视频慕课网APP