Why does Dictionary.Add overwrite all the elements in my dictionary?

I have a dictionary of type Dictionary<string, IEnumerable<string>> and a list of string values. For some reason, every time I do Add, every value in the dictionary is overwritten. I am completely at a dead end why this is happening. I made sure that this is not a reference problem, which is to declare and initialize an IEnumberable object in a loop, so that it does not go beyond a single iteration, and it still does. Here is my code:

 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); } 

where typelist is IEnumerable<string> , root is XElement , and serialLists is my Dictionary.

+6
source share
2 answers

This is a captured iterator issue.

Try:

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

(and the rest is unchanged)

Alternatively, I would evaluate the expression while adding, Ie execute .ToList () in .Add:

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

The second option is probably more effective overall, although it does evaluate those that would otherwise never be needed.

+10
source

The reason is that your IEnumerable<string> sequences are not filled with impatience, but on request, after the foreach completes all its iterations. Thus, when listing any IEnumerable<string> sequence, the type variable will always have the value of the last element in the typelist .

Here is one simple way to fix it:

 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); } 
+6
source

Source: https://habr.com/ru/post/913957/


All Articles