I have the code below which is intended to build a dictionary object with the following construction Dictionary<string<Dictionary<string, string>. For some reason each time I add an item to it the key text is correct but the value (dictionary) overwrites the previous one. This is probably better explained like this:
Iteration 1
- key1, dictionary1
Iteration 2
- key1, dictionary2
- key2, dictionary2
Iteration 3
-
key1, dictionary3
-
key2, dictionary3
- key3, dictionary3
What is causing this and how can I fix this code to stop it overwriting the dictionary in each entry?
QueryNameUserQueryString = new Dictionary<string, string>();
DialectDictionary = new Dictionary<string, Dictionary<string, string>>();
while (dataBaseConnection.NextRecord())
{
if (QueryNameUserQueryString != null)
{
QueryNameUserQueryString.Clear();
}
string dialect = dataBaseConnection.GetFieldById (0);
//If no dialect then carry out next iteration
if (String.IsNullOrEmpty (dialect))
{
continue;
}
try
{
dataBaseConnection2.ExecutePureSqlQuery ("SELECT * FROM " + sqlFactoryTable + " WHERE SQL_FACTORY_DIALECT = '" + dialect + "'");
}
catch
{
dataBaseConnection.Close();
dataBaseConnection2.Close();
throw;
}
//Do we have query strings for this dialect?
if (!dataBaseConnection2.HasRows())
{
continue;
}
//loop through query strings
while (dataBaseConnection2.NextRecord())
{
string queryName = dataBaseConnection2.GetFieldById (2);
string queryString = dataBaseConnection2.GetFieldById (3);
string user = dataBaseConnection2.GetFieldById (4);
//create composite key for dictionary
string compositeKey = dialect + "," + queryName + "," + user;
if (QueryNameUserQueryString != null)
{
//Construct our query string dictionary
QueryNameUserQueryString.Add (compositeKey, queryString);
}
}
//If we have a query string dictionary
if (QueryNameUserQueryString != null)
{
//Ensure m_dialect dictionary is not null
if (DialectDictionary != null)
{
//Construct our dictionary entry for this dialect
DialectDictionary.Add (dialect, QueryNameUserQueryString);
}
}
}
}
You seem to be using the same instance of
QueryNameUserQueryStringon every iteration. When it’s added to theDialectDictionary, it’s added as a reference – not a copy of the original.To “properly” solve the issue, I would move the declaration of your
QueryNameUserQueryStringvariable inside the while-scope. That way you would make sure that it can only exist in the scope of a single iteration, not across several. When it’s added to theDialectDictionary, the reference lives on in that dictionary and you’re safe to leave the scope.