Shamsur Rahim Hemel
Shamsur Rahim Hemel

Reputation: 47

Values in a Dictionary are getting replaced by last value in C#

I have a Dictionary type variable where I'm keeping "string" type key and "List " type values.

The problem is, in case of loop all the previous values are getting replaced by the last value.

Why this happens?

        List<IWebElement> indicationsElement = ReturnIndicationList();
        drugsDB = new List<string>();
        for (int i = 0; i < indicationsElement.Count;i++ )
        {
            string key = indicationsElement[i].Text.ToString();
            dt = ZittarPatt.getDrugsByIndication(ClientName, key);
            drugsDB.Clear();

            for (int k = 0; k < dt.Rows.Count; k++)
            {
                drugsDB.Add(dt.Rows[k].ItemArray[3].ToString().Trim());
            }
            drugsByindicationDictionary.Add(key, drugsDB);
        }

Upvotes: 0

Views: 177

Answers (2)

Orel Eraki
Orel Eraki

Reputation: 12196

You're adding the same reference every iteration instead of adding new instance of List<string>. Every time you use .Clear it clears all the entries at drugsByindicationDictionary which are already the same entry.
Thus, only the last addition to drugsDB will be saved. (No .Clear is used at the end)

You should do the following code:

List<IWebElement> indicationsElement = ReturnIndicationList();
for (int i = 0; i < indicationsElement.Count;i++ )
{
    string key = indicationsElement[i].Text.ToString();
    dt = ZittarPatt.getDrugsByIndication(ClientName, key);
    var drugsDB = new List<string>();

    for (int k = 0; k < dt.Rows.Count; k++)
    {
        drugsDB.Add(dt.Rows[k].ItemArray[3].ToString().Trim());
    }
    drugsByindicationDictionary.Add(key, drugsDB);
}

Upvotes: 2

Mitat Koyuncu
Mitat Koyuncu

Reputation: 928

Change drugsDB.Clear(); to drugsDB = new List<string>();

Upvotes: 0

Related Questions