2012-04-23 19 views
6

我有一個Dictionary<string, IEnumerable<string>>類型的字典和一個字符串值列表。出於某種原因,每次我進行添加時,字典中的每個值都會被覆蓋。至於爲什麼會發生這種情況,我完全被難住了。我確信,在循環中聲明和初始化IEnumberable對象並不是一個引用問題,因此它的作用域不會超出一個迭代範圍,它仍然會執行此操作。這裏是我的代碼:爲什麼Dictionary.Add會覆蓋我的字典中的所有項目?

foreach (string type in typelist) 
{ 
    IEnumerable<string> lst = 
     from row in root.Descendants() 
     where row.Attribute("serial").Value.Substring(0, 3).Equals(type) 
     select row.Attribute("serial").Value.Substring(3).ToLower(); 

    serialLists.Add(type, lst); 
} 

其中typelistIEnumerable<string>rootXElement,並serialLists是我的字典。

+4

你有「關閉了循環變量」。每添加一個'lst'都將使用* last *'type'變量。請閱讀:http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx有趣的是,這個問題將會消失C #5! – dlev 2012-04-23 17:07:19

+1

我一定會閱讀。再次感謝大家的幫助! – Annath 2012-04-23 17:23:56

回答

10

這是一個捕獲的迭代器問題。

嘗試:

foreach (string tmp in typelist) 
{ 
    string type = tmp; 

(其餘不變)

或者,我會添加,即在計算表達式做一個.ToList()中。新增:

    serialLists.Add(type, lst.ToList()); 

第二個選項可能是更有效的整體,雖然它不強制,否則可能永遠需要thigs的評價。

+0

謝謝!這立即解決了問題。 – Annath 2012-04-23 17:23:43

6

的原因是你的IEnumerable<string>序列不被急切地填充,但點播,foreach循環會完成所有的迭代。因此,當枚舉IEnumerable<string>序列時,type變量將總是具有typelist中最後一個元素的值。

這裏是解決它一個簡單的方法:

foreach (string type in typelist) 
{ 
    string typeCaptured = type; 

    IEnumerable<string> lst = 
     from row in root.Descendants() 
     where row.Attribute("serial").Value.Substring(0, 3).Equals(typeCaptured) 
     select row.Attribute("serial").Value.Substring(3).ToLower(); 

    serialLists.Add(typeCaptured, lst); 
} 
相關問題