C# 将 Dictionary.keyscollection 转换为字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1621351/
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.keyscollection to array of strings
提问by leora
I have a Dictionary<string, List<Order>>
and I want to have the list of keys in an array. But when I choose
我有一个Dictionary<string, List<Order>>
,我想要一个数组中的键列表。但是当我选择
string[] keys = dictionary.Keys;
This doesn't compile.
这不编译。
How do I convert KeysCollection
to an array of Strings?
如何转换KeysCollection
为字符串数组?
采纳答案by Thomas Levesque
Assuming you're using .NET 3.5 or later (using System.Linq;
):
假设您使用的是 .NET 3.5 或更高版本 ( using System.Linq;
):
string[] keys = dictionary.Keys.ToArray();
Otherwise, you will have to use the CopyTo method, or use a loop :
否则,您将不得不使用 CopyTo 方法,或使用循环:
string[] keys = new string[dictionary.Keys.Count];
dictionary.Keys.CopyTo(keys, 0);
回答by LJM
Unfortunately, I don't have VS nearby to check this, but I think something like this might work:
不幸的是,我附近没有 VS 来检查这个,但我认为这样的事情可能有用:
var keysCol = dictionary.Keys;
var keysList = new List<???>(keysCol);
string[] keys = keysList.ToArray();
where ??? is your key type.
在哪里 ???是您的密钥类型。
回答by Kim Johansson
Use this if your keys isn't of type string. It requires LINQ.
如果您的密钥不是字符串类型,请使用此选项。它需要 LINQ。
string[] keys = dictionary.Keys.Select(x => x.ToString()).ToArray();
回答by Foxfire
With dictionary.Keys.CopyTo (keys, 0);
和 dictionary.Keys.CopyTo (keys, 0);
If you don't need the array (which you usually don't need) you can just iterate over the Keys.
如果您不需要数组(通常不需要),您可以遍历键。
回答by Craig G
Or perhaps a handy generic extension...
或者也许是一个方便的通用扩展...
public static T2[] ToValueArray<T1, T2>(this Dictionary<T1, T2> value)
{
var values = new T2[value.Values.Count];
value.Values.CopyTo(values, 0);
return values;
}