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

前端 未结 11 899
不思量自难忘°
不思量自难忘° 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 05:59

    LINQ is very effective for juggling with collections.

    Your types and structure are unclear to me, but I will try to fit your example to the best of my ability.

    From your code it appears that, for each item, you are adding to that item everything from its own 'Enumerable' property. This is very simple:

    foreach (var item in Enumerable)
    {
        item = item.AddRange(item.Enumerable));
    }
    

    As a more general example, let's say we want to iterate a collection and remove items where a certain condition is true. Avoiding foreach, using LINQ:

    myCollection = myCollection.Where(item => item.ShouldBeKept);
    

    Add an item based on each existing item? No problem:

    myCollection = myCollection.Concat(myCollection.Select(item => new Item(item.SomeProp)));
    

提交回复
热议问题