如何获取字典中的键列表?

Ath*_*han 143 c# dictionary list

我从来没有得到任何我尝试过的代码.

我想要键而不是值(还).事实证明使用另一个数组太多了,因为我也使用了删除.

Cam*_*mal 285

List<string> keyList = new List<string>(this.yourDictionary.Keys);
Run Code Online (Sandbox Code Playgroud)

  • @JerryGoyal不,没有必要.它只是用来清除"yourDictionary"是否是对象的一部分,在函数中派生或名称是参数的混淆. (12认同)
  • 是否有必要使用"这个". (6认同)
  • 更完整的答案是不要假设 Key 类型是字符串。var keyList = yourDictionary.Keys.ToList(); 或者,如果您想发疯而不使用 var 或 Linq: - 键入 keyType = yourDictionary.GetType().GetGenericArguments()[0]; 类型 listType = typeof(List&lt;&gt;).MakeGenericType(keyType); IList keyList = (IList)Activator.CreateInstance(listType); keyList.AddRange(yourDictionary.Keys); (3认同)

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)

  • @MartinCapodici那么你通常应该期望迭代器打破并拒绝继续 (5认同)
  • Marc,是的,在这种情况下,你会像其他答案那样做一些事情并创建一个新列表. (4认同)
  • 如果你在循环中删除键怎么办? (2认同)

pre*_*rem 39

获取所有密钥的列表

using System.Linq;
List<String> myKeys = myDict.Keys.ToList();
Run Code Online (Sandbox Code Playgroud)

  • 请不要忘记:`使用System.Linq;`我需要知道忽略哪些答案.抱歉:) (13认同)
  • 谢谢@Bitterblue.我无法理解为什么`.ToList()`在我多次使用它时抛出错误,所以我来到这里寻找答案,我意识到我在工作的文件没有`使用系统.Linq` :) (2认同)

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)


Ant*_*oth 6

我不敢相信所有这些令人费解的答案。假设键的类型为:字符串(如果您是懒惰的开发人员,则使用“var”):-

List<string> listOfKeys = theCollection.Keys.ToList();
Run Code Online (Sandbox Code Playgroud)