2009-08-14 51 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(); 
相關問題