Ath*_*han 143 c# dictionary list
我从来没有得到任何我尝试过的代码.
我想要键而不是值(还).事实证明使用另一个数组太多了,因为我也使用了删除.
Cam*_*mal 285
List<string> keyList = new List<string>(this.yourDictionary.Keys);
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 67
你应该能够看看.Keys:
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
foreach (string key in data.Keys)
{
Console.WriteLine(key);
}
Run Code Online (Sandbox Code Playgroud)
pre*_*rem 39
获取所有密钥的列表
using System.Linq;
List<String> myKeys = myDict.Keys.ToList();
Run Code Online (Sandbox Code Playgroud)
Tho*_*rin 12
Marc Gravell的回答应该适合你.myDictionary.Keys返回一个实现一个对象ICollection<TKey>,IEnumerable<TKey>和他们非通用同行.
我只是想补充一点,如果您打算同时访问该值,您可以像这样循环遍历字典(修改示例):
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
foreach (KeyValuePair<string, int> item in data)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
Run Code Online (Sandbox Code Playgroud)
我不敢相信所有这些令人费解的答案。假设键的类型为:字符串(如果您是懒惰的开发人员,则使用“var”):-
List<string> listOfKeys = theCollection.Keys.ToList();
Run Code Online (Sandbox Code Playgroud)