What is the best way to modify a list in a 'foreach' loop?

前端 未结 11 849
不思量自难忘°
不思量自难忘° 2020-11-22 05:23

A new feature in C# / .NET 4.0 is that you can change your enumerable in a foreach without getting the exception. See Paul Jackson\'s blog entry An Interest

11条回答
  •  滥情空心
    2020-11-22 06:06

    Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.

    foreach(var item in Enumerable)
    {
        foreach(var item2 in item.Enumerable.ToList())
        {
            item.Add(item2)
        }
    }
    

提交回复
热议问题