C# dictionary adding to wrong key/value pair
I have the following foreach loop in my program:
Dictionary<string, int[]> summaryDate_clipsEpisodesImps = new Dictionar开发者_C百科y<string, int[]>();
Dictionary<string, int[]> summaryPartner_clipsEpisodesImps = new Dictionary<string, int[]>();
foreach (DataRow row1 in dt10.Rows)
{
int[] numbers = new int[3];
numbers[0] = 0;
numbers[1] = 0;
numbers[2] = 0;
if (!dictionary1.ContainsKey(row1["value1"].ToString().Trim()))
{
dictionary1.Add(row1["value1"].ToString().Trim(), numbers);
}
if (!dictionary2.ContainsKey(row1["value2"].ToString().Trim()))
{
dictionary2.Add(row1["value2"].ToString().Trim(), numbers);
}
if (row1["yes_or_no"].ToString().Trim() == "yes")
{
dictionary1[row1["value1"].ToString().Trim()][0] = dictionary1[row1["value1"].ToString().Trim()][0] + Convert.ToInt32(row1["a_number"]);
dictionary2[row1["value2"].ToString().Trim()][0] = dictionary2[row1["value2"].ToString().Trim()][0] + Convert.ToInt32(row1["a_number"]);
}
}
Essentially, I am looping through a datatable and creating a dictionary of string/int arrays based on values that I find in each record. Then I'm trying to increment the first value in the array based on the presence of another field in the record.
My problem occurs in the if statement when I check for the yes_or_no value. When the second line incrementing dictionary2 is present in this statement, the value in dictionary 1 is incremented by the same value. I have no idea why this is the case.
Please let me know if this isn't entirely clear. Thanks in advance for the help.
This is because the values in both dictionary entries point to the same instance of numbers
. This means any change to one will affect the other.
To put a new instance in each dictionary you could do something similar to:
...
if (!dictionary1.ContainsKey(row1["value1"].ToString().Trim()))
{
dictionary1.Add(row1["value1"].ToString().Trim(), GetNumbersArray());
}
if (!dictionary2.ContainsKey(row1["value2"].ToString().Trim()))
{
dictionary2.Add(row1["value2"].ToString().Trim(), GetNumbersArray());
}
...
private int[] GetNumbersArray()
{
int[] numbers = new int[3];
numbers[0] = 0;
numbers[1] = 0;
numbers[2] = 0;
return numbers;
}
You're adding a pointer to the array to each dictionary. Both dictionaries look at the same array, so when you modify the array through dictionary2, dictionary1 sees the changes.
精彩评论