in c#, what is the fastest way to convert a dictionary of about 100 entries to a list? 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. 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;
}
}
答案 0 :(得分:5)
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. As input the constructor takes the dictionary to read it's values. As noted that is an O(1) operation.
Enumerable.ToList
will create a new list from those values. 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.
答案 1 :(得分:0)
I think this can help:
var list= new List<V>(myDictionary.Values);