开发者

How can i use listDictionary?

开发者 https://www.devze.com 2023-01-03 18:18 出处:网络
i can fill my listdictinary but, if running error returns to me in \"foreach (string ky in ld.Keys)\"(invalid operation Exception was unhandled)

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 crea开发者_高级运维ting 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";


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);
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消