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
This question is related to
c#
.net
arrays
generics
dictionary
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();
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;
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);
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.
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;
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.
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;
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);
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;
Source: Stackoverflow.com