Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Dictionary.Add overwriting all items 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 an Add, every value in the dictionary is overwritten. I'm completely stumped as to why this is happening. I made sure it's not a reference problem be declaring and initializing the IEnumberable object within the loop so that it's scope does not go outside one iteration, and it still does it. 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 an IEnumerable<string>, root is an XElement, and serialLists is my Dictionary.

like image 891
Annath Avatar asked Apr 23 '12 17:04

Annath


People also ask

How do you not overwrite a dictionary in Python?

Add dictionary to dictionary without overwriting in Python.If the key already exists in dict_1 and it is has a value of list type. Then append the value of this key from dict_2 to that list value in dict_1. If the key doesn't exist in dict_1, then add this key-value pair to dict_1.

Does dictionary update overwrite?

Append values to a dictionary using the update() method The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.

How do you set a value in a dictionary in a way that doesn't override existing values?

In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value. By using the setdefault() method, you can add items with new values only for new keys without changing the values for existing keys.


1 Answers

This is a captured iterator problem.

Try:

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

(and the rest unchanged)

Alternatively, I would evaluate the expression during the add, I.e. do a .ToList() in the .Add:

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

The second option is probably more effective overall, although it does force evaluation of thigs that might otherwise never be needed.

like image 101
Marc Gravell Avatar answered Sep 28 '22 18:09

Marc Gravell