Mat*_*ton 117
// 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();
Run Code Online (Sandbox Code Playgroud)
Ste*_*ric 12
将其存储在列表中.它更容易;
List<Foo> arr = new List<Foo>(dict.Values);
Run Code Online (Sandbox Code Playgroud)
当然,如果你特意想要它在数组中;
Foo[] arr = (new List<Foo>(dict.Values)).ToArray();
Run Code Online (Sandbox Code Playgroud)
值上有一个ToArray()函数:
Foo[] arr = new Foo[dict.Count];
dict.Values.CopyTo(arr, 0);
Run Code Online (Sandbox Code Playgroud)
但我不认为它有效(我没有真正尝试过,但我想它会将所有这些值复制到数组中).你真的需要一个阵列吗?如果没有,我会尝试传递IEnumerable:
IEnumerable<Foo> foos = dict.Values;
Run Code Online (Sandbox Code Playgroud)
如果您想使用 linq,那么您可以尝试以下操作:
Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();
Run Code Online (Sandbox Code Playgroud)
我不知道哪个更快或更好。两者都为我工作。