Convert dictionary values into array
C#.NetArraysGenericsDictionaryC# 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);