获得一个KeyValuePair<>直接从字典<>字典、直接、KeyValuePair、LT

2023-09-03 02:21:33 作者:刺眼的青春╮

我有 System.Collections.Generic.Dictionary< A,B>字典其中A和B类,和实例 A一(其中 dict.ContainsKey(一)是真实的)。

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

是否有可能获得包含KeyValuePair A 直接从字典? 或者我需要创建一个新的KeyValuePair:新KeyValuePair&LT; A,B&GT;(一,字典[A])

Is it possible to get the KeyValuePair containing a directly from the Dictionary? Or do I need to create a new KeyValuePair: new KeyValuePair<A, B>(a, dict[a])?

推荐答案

您需要创建一个新的 KeyValuePair 1 - 但是记住这KVP是一个值类型(结构),无论如何,所以它不喜欢你做这个引入一个新的低效率。任何方法返回一个KVP将反正创建副本 - 你只是直接创建实例

You need to create a new KeyValuePair1 - but bear in mind that KVP is a value type (a struct) anyway, so it's not like you're introducing a new inefficiency by doing this. Any method returning a KVP would be creating a copy anyway - you're just creating the instance directly.

您可以随时添加一个扩展方法的IDictionary&LT; TKEY的,TValue&GT; 如果你想要的东西:

You could always add an extension method to IDictionary<TKey, TValue> if you wanted:

public static KeyValuePair<TKey, TValue> GetEntry
    (this IDictionary<TKey, TValue> dictionary,
     TKey key)
{
    return new KeyValuePair<TKey, TValue>(key, dictionary[key]);
}

正如评论指出,这是完全可能的,存储在字典中的关键不在于的一样的规定,只是语义上等于一个 - 通过一些语义,它可以通过一个定制的IEqualityComparer (与不区分大小写的字典,例如。)在这种情况下,code以上不会再回来了字典中的实际条目,但有一个条目关键你提供查找。不幸的是找到原始密钥的任何有效的方式 - 你必须遍历词典:(

As noted in comments, it's entirely possible that the key which is stored in the dictionary is not the same as the one provided, just semantically equal - by some semantics which could be customized by an IEqualityComparer (as with a case-insensitive dictionary, for example.) In that case, the code above would not return the actual entry in the dictionary, but an entry with the key you provided to look up. Unfortunately there's no efficient way of finding the original key - you'd have to iterate over the dictionary :(

1 我知道,你可以遍历字典条目,并找到相应的条目的方式,但我可以看到,为什么你会永远想这样做,当你有没有理由一个非常好的索引是O(1)而不是O(N)。

1 I was aware that you could iterate over the dictionary entries and find the appropriate entry that way, but I can see no reason why you'd ever want to do so when you've got a perfectly good indexer which is O(1) instead of O(N).