'Dictionary AddRange in iteration adds range to both current and previous pointer
I am creating a Project-2-Categories dictionary from supplied Project-2-Groups and Group-2-Categories dictionaries.
In my code example I expected the following result:
{
"P1": [ "1", "11", "111" ],
"P2": [ "1", "11", "111", "2", "22", "222" ],
}
However, the actual result is:
{
"P1": [ "1", "11", "111", "2", "22", "222" ],
"P2": [ "1", "11", "111", "2", "22", "222" ],
}
I would appreciate any help clearing up what I am misunderstanding here.
Link to fiddle
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var proj2categories = new Dictionary<string, List<string>>();
var proj2groups = new Dictionary<string, List<string>>
{
{ "P1", new List<string>{ "Grp1" } },
{ "P2", new List<string>{ "Grp1", "Grp2" } },
};
var group2categories = new Dictionary<string, List<string>>
{
{ "Grp1", new List<string>{ "1", "11", "111" } },
{ "Grp2", new List<string>{ "2", "22", "222" } },
};
foreach (var p2g in proj2groups)
{
var projKey = p2g.Key;
foreach (var agroup in p2g.Value)
{
if (!group2categories.TryGetValue(agroup, out var categories))
continue;
if (proj2categories.ContainsKey(projKey))
proj2categories[projKey].AddRange(categories);
else
proj2categories.Add(projKey, categories);
}
}
Console.WriteLine("Expected: 3. Actual: " + proj2categories["P1"].Count() + " FAILED");
Console.WriteLine("Expected: 1. Actual: " + proj2categories["P1"].First());
Console.WriteLine("Expected: 111. Actual: " + proj2categories["P1"].Last() + " FAILED");
Console.WriteLine("Expected: 6. Actual: " + proj2categories["P2"].Count());
Console.WriteLine("Expected: 1. Actual: " + proj2categories["P2"].First());
Console.WriteLine("Expected: 222. Actual: " + proj2categories["P2"].Last());
}
}
Solution 1:[1]
You can reuse the same instance of list.
However, each time, you must empty it via Clear() before filling it up again in the line with an out parameter, instead of creating a new List<string> instance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rivo R. |
