Fre*_*red 0 c# performance dictionary list
在c#中,将约100个条目的字典转换为列表的最快方法是什么?我目前正在使用
myDictionary.Values.ToList();
Run Code Online (Sandbox Code Playgroud)
但是当我查看Values属性的源代码时,它似乎创建了一个字典的副本,这似乎很慢.我不需要副本,有最快的方法吗?
[__DynamicallyInvokable]
public Dictionary<TKey, TValue>.ValueCollection Values
{
[__DynamicallyInvokable] get
{
if (this.values == null)
this.values = new Dictionary<TKey, TValue>.ValueCollection(this);
return this.values;
}
}
Run Code Online (Sandbox Code Playgroud)
它不会创建字典的副本,它只是创建了嵌套在一个类的实例Dictionary<TKey, TValue>,该Dictionary<TKey,?TValue>.ValueCollection-class.作为输入,构造函数使用字典来读取它的值.如上所述,这是O(1)操作.
Enumerable.ToList将从这些值创建一个新列表.在我看来,这种方法是有效和可读的.通过使用,ToList您可以将字典本身的值解耦,这似乎是您所希望的.