简体   繁体   English

转换字典的最快方法 <K,V> 列出 <V>

[英]Fastest way to convert a Dictionary<K,V> to List<V>

in c#, what is the fastest way to convert a dictionary of about 100 entries to a list? 在C#中,将大约100个条目的字典转换为列表的最快方法是什么? I m currently using 我目前正在使用

myDictionary.Values.ToList();

but when I look at the source code of the Values property, it seems to create a copy of the dictionary, which seems slow. 但是当我查看Values属性的源代码时,似乎创建了字典的副本,这似乎很慢。 I don't need a copy, is there a fastest way? 我不需要副本,有没有最快的方法?

[__DynamicallyInvokable]
    public Dictionary<TKey, TValue>.ValueCollection Values
    {
      [__DynamicallyInvokable] get
      {
        if (this.values == null)
          this.values = new Dictionary<TKey, TValue>.ValueCollection(this);
        return this.values;
      }
    }

It doesn't create a copy of the dictionary, it just creates an instance of a class that is nested in Dictionary<TKey, TValue> , the Dictionary<TKey, TValue>.ValueCollection -class . 它不会创建字典的副本,而只是创建嵌套在Dictionary<TKey, TValue>Dictionary<TKey, TValue>.ValueCollection -class中的类的Dictionary<TKey, TValue>.ValueCollection As input the constructor takes the dictionary to read it's values. 作为输入, 构造函数使用字典读取其值。 As noted that is an O(1) operation. 如前所述,这是O(1)运算。

Enumerable.ToList will create a new list from those values. Enumerable.ToList将根据这些值创建一个新列表。 In my opinion this approach is efficient and readable. 我认为这种方法是有效且易读的。 By using ToList you are uncoupling the values from the dictionary itself which seems to be desired. 通过使用ToList您可以将似乎需要的字典本身中的值解耦。

我认为这可以帮助:

var list= new List<V>(myDictionary.Values);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM