C# 将字典值转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/197059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert dictionary values into array
提问by leora
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[]
例如,如果我有一个Dictionary
where Key
isString
和Value
is Foo
,我想得到Foo[]
I am using VS 2005, C# 2.0
我使用的是 VS 2005,C# 2.0
采纳答案by Matt Hamilton
// 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();
回答by Grzenio
There is a ToArray() function on Values:
值上有一个 ToArray() 函数:
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:
IEnumerable<Foo> foos = dict.Values;
回答by Steztric
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();
回答by Piotr Czy?
If you would like to use linq, so you can try following:
如果您想使用 linq,那么您可以尝试以下操作:
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.
我不知道哪个更快或更好。两者都为我工作。
回答by Lior Kirshner
These days, once you have LINQ available, you can convert the dictionary keys and their values to a single string.
现在,一旦有了可用的 LINQ,就可以将字典键及其值转换为单个字符串。
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);