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

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

    To illustrate Nippysaurus's answer: If you are going to add the new items to the list and want to process the newly added items too during the same enumeration then you can just use for loop instead of foreach loop, problem solved :)

    var list = new List();
    ... populate the list ...
    
    //foreach (var entryToProcess in list)
    for (int i = 0; i < list.Count; i++)
    {
        var entryToProcess = list[i];
    
        var resultOfProcessing = DoStuffToEntry(entryToProcess);
    
        if (... condition ...)
            list.Add(new YourData(...));
    }
    

    For runnable example:

    void Main()
    {
        var list = new List();
        for (int i = 0; i < 10; i++)
            list.Add(i);
    
        //foreach (var entry in list)
        for (int i = 0; i < list.Count; i++)
        {
            var entry = list[i];
            if (entry % 2 == 0)
                list.Add(entry + 1);
    
            Console.Write(entry + ", ");
        }
    
        Console.Write(list);
    }
    

    Output of last example:

    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9,

    List (15 items)
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    1
    3
    5
    7
    9

提交回复
热议问题