慕田峪4524236
不幸的是,你不能这样做。Dictionary<TKey, TValue>公开一个方法是完全合理的bool TryGetEntry(TKey key, KeyValuePair<TKey, TValue> entry),但它并没有这样做。正如评论中所建议的那样,最简单的方法可能是使字典中的每个值都具有与字典中的键相同的键。所以: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方法,以便调用者永远不需要知道“内部”字典的样子。
冉冉说
即使大小写与键不匹配,您也可以使用以下利用 LINQ 的代码来获取字典键值对。注意:此代码可用于任何大小的字典,但它最适合较小大小的字典,因为 LINQ 基本上是一一检查每个键值对,而不是直接转到所需的键值对。Dictionary<string,int> dictionary1 = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase){ {"abc1",1}, {"abC2",2}, {"abc3",3} } ;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