如何在循环中更新C#哈希表?

z-b*_*oss 10 c# loops hashtable data-structures

我正在尝试更新循环中的哈希表,但收到错误:System.InvalidOperationException:Collection已被修改; 枚举操作可能无法执行.

private Hashtable htSettings_m = new Hashtable();
htSettings_m.Add("SizeWidth", "728");
htSettings_m.Add("SizeHeight", "450");
string sKey = "";
string sValue = "";
foreach (DictionaryEntry deEntry in htSettings_m)
{
    // Get value from Registry and assign to sValue.
    // ...
    // Change value in hashtable.
    sKey = deEntry.Key.ToString();
    htSettings_m[sKey] = sValue;
}
Run Code Online (Sandbox Code Playgroud)

有没有方法或者为此目的有更好的数据结构?

kei*_*en7 14

你可以先将密钥集合读入另一个IEnumerable实例,然后再遍历该列表

        System.Collections.Hashtable ht = new System.Collections.Hashtable();

        ht.Add("test1", "test2");
        ht.Add("test3", "test4");

        List<string> keys = new List<string>();
        foreach (System.Collections.DictionaryEntry de in ht)
            keys.Add(de.Key.ToString());

        foreach(string key in keys)
        {
            ht[key] = DateTime.Now;
            Console.WriteLine(ht[key]);
        }
Run Code Online (Sandbox Code Playgroud)


Dav*_*man 5

在概念上,我会这样做:

Hashtable table = new Hashtable(); // ps, I would prefer the generic dictionary..
Hashtable updates = new Hashtable();

foreach (DictionaryEntry entry in table)
{
   // logic if something needs to change or nog
   if (needsUpdate)
   {
      updates.Add(key, newValue);
   }
}

// now do the actual update
foreach (DictionaryEntry upd in updates)
{
   table[upd.Key] = upd.Value;
}
Run Code Online (Sandbox Code Playgroud)