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

标签 c# data-structures loops hashtable

我试图在循环中更新哈希表,但出现错误:System.InvalidOperationException: Collection was modified;枚举操作可能不会执行。

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

是否有解决办法,或者是否有更好的数据结构用于此目的?

最佳答案

您可以先将键的集合读入另一个 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]);
        }

关于c# - 如何在循环中更新 C# 哈希表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/326757/

相关文章:

c# - SQL 服务器 : concat or multiple SELECT queries in gridview?

c# - 将 Claims 添加到 ApplicationUser 的子类

c# - 散列范围

c++ - 结构初始化

python - 如何在列表中循环更多次 python 中的列表大小?

javascript - 如何使用 setInterval 和clearInterval 获得延迟

c# - 获取所有数据的一个查询与 300 个特定查询

c# - .NET OWIN 身份验证 - Cookie + Windows(事件目录)

java - 双查 map

javascript - 如何在脚本第一次运行时在 Javascript 中打印一组名称,然后在第二次运行时出现提示?