将字典值转换为数组

时间:2008-10-13 09:04:01

标签: c# .net arrays generics dictionary

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

例如,如果我有Dictionary KeyStringValueFoo,我想Foo[] < / p>

我正在使用VS 2005,C#2.0

5 个答案:

答案 0 :(得分:112)

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

答案 1 :(得分:11)

将其存储在列表中。这更容易;

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

当然,如果你特意想要它在数组中;

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

答案 2 :(得分:5)

值上有一个ToArray()函数:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

但我不认为它有效(我没有真正尝试过,但我想它会将所有这些值复制到数组中)。你真的需要一个阵列吗?如果没有,我会尝试传递IEnumerable:

IEnumerable<Foo> foos = dict.Values;

答案 3 :(得分:4)

如果您想使用linq,那么您可以尝试以下操作:

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

我不知道哪一个更快或更好。两者都适合我。

答案 4 :(得分:1)

现在,一旦有LINQ可用,就可以将字典键及其值转换为单个字符串。

您可以使用以下代码:

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