tags:

views:

34

answers:

2

i can fill my listdictinary but, if running error returns to me in " foreach (string ky in ld.Keys)"(invalid operation Exception was unhandled)

Error Detail : After creating a pointer to the list of sample collection has been changed. C#

       ListDictionary ld = new ListDictionary();
            foreach (DataColumn dc in dTable.Columns)
            {
                MessageBox.Show(dTable.Rows[0][dc].ToString());
                ld.Add(dc.ColumnName, dTable.Rows[0][dc].ToString());
            }

            foreach (string ky in ld.Keys)
                if (int.TryParse(ld[ky].ToString(), out QuantityInt))
                    ld[ky] = "integer";
                else if(double.TryParse(ld[ky].ToString(), out QuantityDouble))
                    ld[ky]="double";
                else
                    ld[ky]="nvarchar";
A: 

You cannot modify a collection within a foreach loop.
Instead you need to use a for loop.

Sani Huttunen
+2  A: 

Your second foreach loop alters the ListDictionary by setting ld[ky] = "whatever"; You can't do this with a foreach loop, because internally it uses an enumerator. While using an enumerator it is illegal to alter the collection being enumerated.

Instead, use a for loop.

Even better, do the whole thing in a single loop on dTable.Columns, setting the value in the dictionary when you are adding each item.

ListDictionary ld = new ListDictionary();
foreach (DataColumn dc in dTable.Columns)
{
     MessageBox.Show(dTable.Rows[0][dc].ToString());

     string value;
     if (int.TryParse(dTable.Rows[0][dc].ToString(), out QuantityInt))
           value = "integer";
     else if(double.TryParse(dTable.Rows[0][dc].ToString(), out QuantityDouble))
           value="double";
      else
           value="nvarchar";

     ld.Add(dc.ColumnName, value);
}
Daniel Dyson