如何将字典的值列表最有效地转换为数组?
例如,如果我有一个键是字符串类型而值是 Foo 类型 的 Dictionary,我想获得 Foo[] 数组。
我正在使用 VS 2005,C# 2.0。
如何将字典的值列表最有效地转换为数组?
例如,如果我有一个键是字符串类型而值是 Foo 类型 的 Dictionary,我想获得 Foo[] 数组。
我正在使用 VS 2005,C# 2.0。
// 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();
将其存储在列表中。这样更容易;
List<Foo> arr = new List<Foo>(dict.Values);
当然,如果你特别想要它在一个数组中;
Foo[] arr = (new List<Foo>(dict.Values)).ToArray();
Values 上有一个 ToArray() 函数:
Foo[] arr = new Foo[dict.Count];
dict.Values.CopyTo(arr, 0);
但我认为这不是很有效率的(虽然我没有真正尝试过,但我猜它会将所有这些值复制到数组中)。你真的需要一个数组吗?如果不需要,我建议尝试传递IEnumerable:
IEnumerable<Foo> foos = dict.Values;
如果你想使用linq,可以尝试以下方法:
Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();
我不知道哪个更快或更好。两者对我都可以使用。
dict.Values.ToArray()
的作用与使用委托逐个生成值的方法相同,但它避免了每个值都需要生成委托所带来的额外开销。 - Lance U. Matthews// 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);
using System.Linq;
。 - Christian Davén