2013-02-26 42 views
0

我正在查字典。 我有2點字典:如何在字典中搜索?

Dictionary<int, string> dict = new Dictionary<int, string>() 
Dictionary<int, int> temp = new Dictionary<int, int>() 

然後香港專業教育學院填充本字典有:

dict.Add(123, ""); 
dict.Add(124, ""); //and so on 

的話,我想循環,雖然這本字典和召回的關鍵,並添加到其他字典

for (int i = 0; i < dict.Count; i++) 
{ 
    if (dict[i] == "") 
    { 
     temp.Add(dict[dict.ElementAt(i).Key],0); 
     dict[dict.ElementAt(i).Value] = "Moved"; 
    } 
} 

我將在這個forloop裏面做其他事情,所以我不能改變它到一個foreach循環。我試圖檢查字典詞典的值是否爲空然後採取密鑰並將鍵值複製到溫度字典,但我收到錯誤。 請幫助:)

即時通訊設法解決的問題是,我想能夠搜索詞典中的值爲「」,並拿起密鑰,並將其存儲在另一個詞典溫度(這將稍後保持第二個值)。我需要在for循環中執行此操作,因爲我希望能夠通過更改i的值來返回。

我想能夠使用我從詞典詞典中選擇鍵和值。

我得到的錯誤只是從字符串轉換爲int,我無法讓它甚至將字典中的密鑰存儲到int變量中。

+4

你會得到什麼錯誤? – 2013-02-26 21:43:38

+6

_「但我得到錯誤」_小心分享這些? – gdoron 2013-02-26 21:43:57

+1

如果你的鍵是連續的(這是for循環所假設的),那麼'Dictionary'並不是真正的最佳容器。只需使用一個列表/數組。 – 2013-02-26 21:45:21

回答

0

您需要將值放在temp字典中。我選擇了0.

 Dictionary<int, string> dict = new Dictionary<int, string>(); 
     Dictionary<int, int> temp = new Dictionary<int, int>(); 

     dict.Add(123, ""); 
     dict.Add(124, ""); //and so on 

     int[] keys = dict.Keys.ToArray(); 
     for (int i = 0; i < dict.Count; i++) 
     { 
      if (dict[keys[i]] == "") 
      { 
       temp.Add(keys[i],0); 
       dict[keys[i]] = "Moved"; 
      } 
     } 
+0

您的解決方案已修復它,謝謝,這是幫助我的鍵陣列的添加:) – user1348463 2013-02-26 22:21:23

+0

很好地使用格式化的第一個答案 – 2013-02-26 22:26:14

0

我認爲這是你要找的東西:

Dictionary<int, string> dict = new Dictionary<int, string>(); 
List<int> temp = new List<int>(); 


dict.Add(123, ""); 
dict.Add(124, ""); //and so on 

foreach (int key in dict.Keys.ToList()) 
{ 
      if (dict[key] == "") 
      { 
       temp.Add(key); 
       dict[key] = "Moved"; 
      } 
     } 
} 

* 首先,通知temp列表,不是字典,因爲你只需添加鍵,沒有key => value(如果你能更好地解釋你爲什麼需要這個字典的話可以更改它)...
其次,注意我用dict.Keys來獲取字典中的所有鍵。我還用ToList()因此它可以在foreach循環工作...

0

你得到一個編譯錯誤的字典中的定義

Dictionary<int, int> temp = new Dictionary<int, temp>(); // int, temp? 

如果是這樣,

Dictionary<int, int> temp = new Dictionary<int, int>(); // int, int 

,或者你得到一個錯誤與此:

temp.Add(dict[dict.ElementAt(i).Key]); 

,因爲你只需添加一個鍵,沒有任何價值。它會像

temp.Add(i, dict[i]); ? 

如果你只是使用臨時保存密鑰值,你不想要一個解釋,你可能HashSet的(只鍵,沒有鍵+值)

如果你正確地解釋你想要解決的問題,這可能是你可以用單個linq語句輕鬆做到的事情嗎?

+0

編輯我的問題,試圖讓它更清楚我在做什麼。 – user1348463 2013-02-26 22:09:28

0

爲什麼temp是字典?我將使用一個List<int>與字典的所有鍵與空(空?)值。

List<int> keysWithEmptyValuesInDictionary = dict 
    .Where(kvp => string.IsNullOrEmpty(kvp.Value)) 
    .Select(kvp => kvp.Key) 
    .ToList(); 
foreach (int key in keysWithEmptyValuesInDictionary) 
{ 
    dict[key] = "moved"; 
}