Convert dictionary values into array

C#.NetArraysGenericsDictionary

C# Problem Overview


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

C# Solutions


Solution 1 - C#

// 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();

Solution 2 - C#

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();

Solution 3 - C#

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;

Solution 4 - C#

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.

Solution 5 - C#

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Matt HamiltonView Answer on Stackoverflow
Solution 2 - C#SteztricView Answer on Stackoverflow
Solution 3 - C#GrzenioView Answer on Stackoverflow
Solution 4 - C#Piotr CzyżView Answer on Stackoverflow
Solution 5 - C#Lior KirshnerView Answer on Stackoverflow