Help me understand something please.
I’m parsing a csv file into a dictionary of lists. I’ve been trying with this code for hours, but every time I print my output I only end up with the last list filling every slot in the dictionary.
public static Dictionary<int, List<string[]>> prefixes = new Dictionary<int, List<string[]>>();
List<string[]> currentGroup = new List<string[]>();
while ((line = reader.ReadLine()) != null) {
row = line.Split(',');
if (count <= 1) {
header.Add(row);
}
else {
curIndex = int.Parse(row[0]);
if (curIndex != lastIndex) {
prefixes.Add(lastIndex, currentGroup);
currentGroup.Clear();
}
currentGroup.Add(row);
lastIndex = curIndex;
}
count++;
}
// Add the remaining group
prefixes.Add(lastIndex, currentGroup);
That is I have for example in my file:
0, abc, 123
1, def, 456
and expect it to output the same, but instead I get:
1, def, 456
1, def, 456
For some reason I decided to try replacing currentGroup.Clear() with currentGroup = new List<string[ ]>(); and everything worked!
public static Dictionary<int, List<string[]>> prefixes = new Dictionary<int, List<string[]>>();
List<string[]> currentGroup = new List<string[]>();
while ((line = reader.ReadLine()) != null) {
row = line.Split(',');
if (count <= 1) {
header.Add(row);
}
else {
curIndex = int.Parse(row[0]);
if (curIndex != lastIndex) {
prefixes.Add(lastIndex, currentGroup);
currentGroup = new List<string[]>(); //////////////// Replaced Clear() with new List
}
currentGroup.Add(row);
lastIndex = curIndex;
}
count++;
}
// Add the remaining group
prefixes.Add(lastIndex, currentGroup);
Can someone please shed some light on why this is happening? Is Clear actually clearing the List that is already added to my Dictionary as well? Is this a C# feature or a programming feature? I’m very confused, but mostly happy that I managed to find the problem after spending hour after hour staring at this tiny piece of code. I just want to avoid making the same mistake again later on.