在添加和删除项的同时,继续迭代HashSet

本文关键字:继续 迭代 HashSet 添加 删除 | 更新日期: 2023-09-27 18:27:02

如何在添加和删除项的同时迭代HashSet?请记住,在实际程序中,有时不会向列表中添加任何内容,因此列表是有结尾的,它不是一个无休止的循环。

例如:

static HashSet<int> listThingy = new HashSet<int>() { 1, 2 } ;
static void Main(string[] args)
{
    foreach (var item in listThingy)
    {
        listThingy.Add(3);
        listThingy.Remove(item);
        Console.WriteLine(item);
    }
}

输出应该是这样的:

1
2
3
3
3
3
3
3
etc..

在程序中,我将向列表中添加随机值(有时不会添加任何值),直到所有值都被处理完毕。

在添加和删除项的同时,继续迭代HashSet

最接近您描述的是:

static ConcurrentDictionary<int, object> listThingy = new ConcurrentDictionary<int, object>();
static void Main(string[] args)
{
    listThingy.Add(1, null);
    listThingy.Add(2, null);
    foreach (var item in listThingy)
    {
        object val = null;
        listThingy.TryAdd(3, null);
        listThingy.TryRemove(2, val);
        Console.WriteLine(item);
    }
}