将字典值转换为数组

将字典的值列表转换为数组的最有效方法是什么?

例如,如果我有一个 Dictionary,其中 KeyStringValueFoo,我想得到 Foo[]

我使用的是 VS 2005,C # 2.0

185788 次浏览
// 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();

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;

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

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.

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