C# 无法将 keyValuePair 直接添加到 Dictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13012260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:20:22  来源:igfitidea点击:

Can't add keyValuePair directly to Dictionary

c#dictionarykey-valuegeneric-collections

提问by Dave

I wanted to add a KeyValuePair<T,U>to a Dictionary<T, U>and I couldn't. I have to pass the key and the value separately, which must mean the Add method has to create a new KeyValuePair object to insert, which can't be very efficient. I can't believe there isn't an Add(KeyValuePair<T, U>)overload on the Add method. Can anyone suggest a possible reason for this apparent oversight?

我想将 a 添加KeyValuePair<T,U>到 a Dictionary<T, U>,但我不能。我必须分别传递键和值,这意味着 Add 方法必须创建一个新的 KeyValuePair 对象才能插入,这不是很有效。我不敢相信Add(KeyValuePair<T, U>)Add 方法没有重载。任何人都可以提出这种明显疏忽的可能原因吗?

采纳答案by Tim Copenhaver

Backup a minute...before going down the road of the oversight, you should establish whether creating a new KeyValuePair is really so inefficient.

备份一分钟......在走上监督之路之前,您应该确定创建一个新的 KeyValuePair 是否真的如此低效。

First off, the Dictionary class is not internally implemented as a set of key/value pairs, but as a bunch of arrays. That aside, let's assume it was just a set of KeyValuePairs and look at efficiency.

首先,Dictionary 类不是作为一组键/值对在内部实现的,而是作为一堆数组实现的。除此之外,让我们假设它只是一组 KeyValuePairs 并看看效率。

The first thing to notice is that KeyValuePairis a structure. The real implication of that is that it has to be copied from the stack to the heap in order to be passed as a method parameter. When the KeyValuePair is added to the dictionary, it would have to be copied a second time to ensure value type semantics.

首先要注意的是KeyValuePair是一个结构。真正的含义是它必须从堆栈复制到堆才能作为方法参数传递。当 KeyValuePair 添加到字典中时,必须再次复制它以确保值类型语义。

In order to pass the Key and Value as parameters, each parameter may be either a value type or a reference type. If they are value types, the performance will be very similar to the KeyValuePair route. If they are reference types, this can actually be a faster implementation since only the address needs to be passed around and very little copying has to be done. In both the best case and worst case, this option is marginally better than the KeyValuePair option due to the increased overhead of the KeyValuePair struct itself.

为了将 Key 和 Value 作为参数传递,每个参数可以是值类型或引用类型。如果它们是值类型,则性能将与 KeyValuePair 路由非常相似。如果它们是引用类型,这实际上可以是一个更快的实现,因为只需要传递地址并且只需要进行很少的复制。在最好的情况和最坏的情况下,由于 KeyValuePair 结构本身的开销增加,此选项略好于 KeyValuePair 选项。

回答by DmitryG

You can use the IDictionary<TKey,TValue>interface which provides the Add(KeyValuePair<TKey,TValue>)method:

您可以使用IDictionary<TKey,TValue>提供该Add(KeyValuePair<TKey,TValue>)方法的接口:

IDictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(new KeyValuePair<int,string>(0,"0"));
dictionary.Add(new KeyValuePair<int,string>(1,"1"));

回答by Richard

There is such a method – ICollection<KeyValuePair<K, T>>.Addbut as it is explicitlyimplemented you need to cast your dictionary object to that interface to access it.

有这样一种方法——ICollection<KeyValuePair<K, T>>.Add但是由于它是明确实现的,因此您需要将字典对象转换为该接口才能访问它。

((ICollection<KeyValuePair<KeyType, ValueType>>)myDict).Add(myPair);

See

The pageon this method includes an example.

此方法的页面包含一个示例。

回答by Gertjan Assies

I'm not 100% sure, but I think the internal implementation of a Dictionary is a Hash-table, which means key's are converted to hashes to perform quick look ups.

我不是 100% 确定,但我认为字典的内部实现是一个哈希表,这意味着键被转换为哈希以执行快速查找。

Have a read here if you want to know more about hashtables

如果您想了解有关哈希表的更多信息,请阅读此处

http://en.wikipedia.org/wiki/Hash_table

http://en.wikipedia.org/wiki/Hash_table

回答by Mike Corcoran

just because the enumerator for the Dictionary class returns a KeyValuePair, does not mean that is how it is implemented internally.

仅仅因为 Dictionary 类的枚举器返回一个 KeyValuePair,并不意味着它在内部是如何实现的。

use IDictionary if you really need to pass KVP's because you've already got them in that format. otherwise use assignment or just use the Add method.

如果您确实需要通过 KVP,请使用 IDictionary,因为您已经以这种格式获得了它们。否则使用赋值或仅使用 Add 方法。

回答by WiiMaxx

Should somebody really want to do this, here is an Extension

如果有人真的想这样做,这里是一个扩展

    public static void Add<T, U>(this IDictionary<T, U> dic, KeyValuePair<T, U> KVP)
    {
        dic.Add(KVP.Key, KVP.Value);
    }

but i would recommend to not do this if there is no real need to do this

但如果没有真正需要这样做,我会建议不要这样做

回答by Machtyn

Unless I'm mistaken, .NET 4.5 and 4.6 adds the ability to add a KeyValuePair to a Dictionary. (If I'm wrong, just notify me and I'll delete this answer.)

除非我弄错了,.NET 4.5 和 4.6 增加了将 KeyValuePair 添加到字典的能力。(如果我错了,请通知我,我会删除此答案。)

https://msdn.microsoft.com/en-us/library/cc673027%28v=vs.110%29.aspx

https://msdn.microsoft.com/en-us/library/cc673027%28v=vs.110%29.aspx

From the above link, the relevant piece of information is this code example:

从上面的链接,相关信息是这个代码示例:

public static void Main() 
{
    // Create a new dictionary of strings, with string keys, and 
    // access it through the generic ICollection interface. The 
    // generic ICollection interface views the dictionary as a 
    // collection of KeyValuePair objects with the same type 
    // arguments as the dictionary. 
    //
    ICollection<KeyValuePair<String, String>> openWith =
        new Dictionary<String, String>();

    // Add some elements to the dictionary. When elements are  
    // added through the ICollection<T> interface, the keys 
    // and values must be wrapped in KeyValuePair objects. 
    //
    openWith.Add(new KeyValuePair<String,String>("txt", "notepad.exe"));
    openWith.Add(new KeyValuePair<String,String>("bmp", "paint.exe"));
    openWith.Add(new KeyValuePair<String,String>("dib", "paint.exe"));
    openWith.Add(new KeyValuePair<String,String>("rtf", "wordpad.exe"));

    ...
}

As can be seen, a new object of type Dictionary is created and called openWith. Then a new KVP object is created and added to openWithusing the .Addmethod.

可以看出,创建并调用了一个 Dictionary 类型的新对象openWith。然后openWith使用该.Add方法创建并添加一个新的 KVP 对象。

回答by Machtyn

What would be wrong with just adding it into your project as an extension?

将它作为扩展添加到您的项目中会有什么问题?

namespace System.Collection.Generic
{
    public static class DictionaryExtensions
    {
        public static void AddKeyValuePair<K,V>(this IDictionary<K, V> me, KeyValuePair<K, V> other)
        {
            me.Add(other.Key, other.Value);
        }
    }
}