I’m having trouble with this bit of code. I’m new to C#, but from what I’ve done so far I’m drawing the conclusion that dictionaries are only references, and do not actually store data?
foreach (Microsoft.Office.Interop.Excel.Range row in range1.Rows)
{
string upc;
upc = row.Cells[1, 2].Value2;
list.Add(upc);
list.Add(row.Cells[1, 3].Value2);
list.Add("6");
//add row to dictionary
dictionary.Add(row.Cells[1, 1].Value2, list);
}
In this example, if I keep this loop going for every row in range1, it will add every row’s data to the list. IE, the last item in the dictionary will contain each attribute for all of the rows in the range. I tried clearing the list after every iteration, but then the dictionary reports that there is no value, leading me to believe that I must have a separate list created for each dictionary entry? How can I do this, and is this the most efficient way? Something seems off. Thanks!
It looks like there’s only one list in your code, and a reference to it is stored as the value for each dictionary key. You want to create a new List at each loop iteration and add it to the dictionary.