Getting a KeyValuePair<> directly from a Dictionary<>

后端 未结 4 1431
忘了有多久
忘了有多久 2021-01-03 18:15

I have System.Collections.Generic.Dictionary dict where A and B are classes, and an instance A a (where dict.ContainsKey(a)

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 18:37

    We can't get to "IPHone" this way:

    var dict = new Dictionary(StringComparer.OrdinalIgnoreCase)
                   {
                       { "IPHone", "TCP/IP honing tools" }
                   };
    
    Console.WriteLine(dict["iPhone"]); // "TCP/IP honing tools"
    Console.WriteLine( ??? ); // "IPHone"
    

    There's seems to be no O(1) solution with the current API, but looping through all entries works:

    var keyValue = dict.First(p => dict.Comparer.Equals(p.Key, "iPhone"));
    
    Console.WriteLine(keyValue.Key); // "IPHone"
    Console.WriteLine(keyValue.Value); // "TCP/IP honing tools"
    

    Or as an extension for the lazy:

    [Pure]
    public static KeyValuePair GetEntry(this Dictionary dictionary, TKey key)
    {
        var comparer = dictionary.Comparer;
        return dictionary.FirstOrDefault(p => comparer.Equals(p.Key, key));
    }
    

提交回复
热议问题