97

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

For example, if I have a Dictionary where Key is String and Value is Foo, I want to get Foo[]

I am using VS 2005, C# 2.0

5 Answers 5

152
// 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();
Sign up to request clarification or add additional context in comments.

6 Comments

Does the extension .ToArray<Foo>() perform any better?
but how do we know that it's the most efficient ?
@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. :)
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.
ToArray() is an extension method in LINQ, so you need to add using System.Linq;
|
17

Store it in a list. It is easier;

List<Foo> arr = new List<Foo>(dict.Values);

Of course if you specifically want it in an array;

Foo[] arr = (new List<Foo>(dict.Values)).ToArray();

Comments

7

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;

Comments

6

If you would like to use linq, so you can try following:

Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();

I don't know which one is faster or better. Both work for me.

1 Comment

dict.Values.ToArray() does the same thing, but without the overhead of materializing each value through a delegate.
3

These days, once you have LINQ available, you can convert the dictionary keys and their values to a single string.

You can use the following code:

// convert the dictionary to an array of strings
string[] strArray = dict.Select(x => ("Key: " + x.Key + ", Value: " + x.Value)).ToArray();

// convert a string array to a single string
string result = String.Join(", ", strArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.