2009-08-14 53 views

回答

220
List<string> keyList = new List<string>(this.yourDictionary.Keys); 
+4

是否需要使用“this”。 – JerryGoyal 2015-09-30 07:45:26

+8

@JerryGoyal不,没有必要。它只是简单地用于清楚“yourDictionary”是否是对象的一部分,在函数中派生或参数名称的混淆。 – bcdan 2015-11-05 12:09:59

64

你应该能够只看.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); 
    } 
+1

如果你要删除循环中的键? – 2016-03-10 22:17:47

+4

@MartinCapodici然后你通常应该期望迭代器打破并拒绝继续 – 2016-03-10 22:32:15

+2

Marc,是的,所以在这种情况下,你会做类似于其他答案的东西并创建一个新列表。 – 2016-03-10 23:01:37

11

马克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); 
} 
3

的问题是有点棘手理解,但我猜测问题在于你在迭代键时尝试从字典中移除元素。我认为在这种情况下,你别无选择,只能使用第二个数组。

ArrayList lList = new ArrayList(lDict.Keys); 
foreach (object lKey in lList) 
{ 
    if (<your condition here>) 
    { 
    lDict.Remove(lKey); 
    } 
} 

如果你可以使用通用的列表和字典,而不是一个ArrayList的话,我会,但上面的应该只是工作。

0

或者这样:

List< KeyValuePair< string, int > > theList = 
    new List< KeyValuePair< string,int > >(this.yourDictionary); 

for (int i = 0; i < theList.Count; i++) 
{ 
    // the key 
    Console.WriteLine(theList[i].Key); 
} 
+0

这是否会创建密钥副本? (这样你可以安全地枚举) – mcmillab 2012-12-20 21:28:05

1

我认为最简洁的方式是使用LINQ

Dictionary<string, int> data = new Dictionary<string, int>(); data.Select(x=>x.Key).ToList();

+1

这可能是“整洁”的方式,但它也是非常昂贵的方式。首先,虽然数据。键将是O(1)操作,并不会真正分配任何东西,您的解决方案将是O(N),并将分配一个新的集合(列表)与所有键。所以,请不要这样做。 – 2017-05-18 04:06:20

30

要获得所有按键的列表

List<String> myKeys = myDict.Keys.ToList(); 
+7

请不要忘记:'使用System.Linq;'我需要知道要忽略哪些答案。对不起:) – Bitterblue 2016-06-06 11:17:05

+2

谢谢@Bitterblue。我无法理解为什么'.ToList()'在我多次使用它时抛出一个错误,所以我来到这里寻找答案,并且我意识到我正在工作的文件没有'使用System .Linq' :) – Drew 2016-09-16 20:27:08

+0

不起作用:'Dictionary .KeyCollection'不包含'ToList''的定义 – sakra 2017-04-10 09:47:19

0

适用于混合动力词典tionary,我使用这样的:

List<string> keys = new List<string>(dictionary.Count); 
keys.AddRange(dictionary.Keys.Cast<string>()); 
-2

我常采用这种获得字典内的键和值:(VB.Net)

For Each kv As KeyValuePair(Of String, Integer) In layerList 

Next 

(layerList是类型字典的(字符串,整数))

0

我不能相信所有这些令人费解的答案。假设密钥的类型是:string(或者如果你是一个懒惰的开发者,则使用'var'): -

List<string> listOfKeys = theCollection.Keys.ToList(); 
相关问题