views:

5708

answers:

2

what is the most efficient way of turning the list of values of a dictionary into an array

for example, if i have:

Dictionary where key is string and value is Foo

i want to get Foo[]

I am using VS 2005, C# 2.0

+14  A: 
// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();
Matt Hamilton
Does the extension .ToArray<Foo>() perform any better?
Goran
but how do we know that it's the most efficient ?
Tom Carter
I can't see how ToArray() could be any faster than the straight copy - which seems to be minimalistic.
Samuel Kim
@Tom I usually take the view that anything built into the framework (like .CopyTo() or .ToArray()) is the most efficient way to do it. The Microsofties are smarter than me. :)
Matt Hamilton
ToArray is less performant than CopyTo (it uses CopyTo to copy to an internal intermediate representation, and then Copy again to return it out). However, as with all micro-performance related matters go for readability, robustness and maintainability and measure performance if it's an issue.
ICR
+3  A: 

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;
Grzenio