Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying list inside foreach loop

Tags:

c#

foreach

list

I have a construction similar to this (but a lot more complicated):

var list = new List<string>();

// .. populate list ..

foreach(var item in list)
{
    DoFunction(list);
}

public void DoFunction(List<string> list)
{
    if(someCondition == true)
    {
        // .. modify list in here ..
    }
}

Now, I understand that its not possible to edit the collection you're foreaching through, but how do you jump out of the loop gracefully if you do have to edit the list (without a try catch statement)? Is there some way to tell if the list has been edited? Can you edit the list and quickly break; before it notices?

like image 475
Entity Avatar asked Jun 09 '11 15:06

Entity


People also ask

Can we modify List in foreach?

Modify a C# collection with foreach by using a second collection. Since we cannot change a collection directly with foreach , an alternative is to use a second collection. To that second collection we then add new elements. This way we can still benefit from the simplicity that foreach offers.

Does foreach work with lists?

Using the CodeThe ForEach method of the List<T> (not IList<T> ) executes an operation for every object which is stored in the list. Normally it contains code to either read or modify every object which is in the list or to do something with list itself for every object.

How do I remove an item from a foreach?

To remove element from array in forEach loop with JavaScript, we can use the array splice method. const review = ["a", "b", "c", "b", "a"]; review. forEach((item, index, arr) => { if (item === "a") { arr. splice(index, 1); } });

Can we put condition in foreach?

No, a foreach simply works for each element.


2 Answers

Yes, you could break, if that's what you really want. An exception won't be thrown until the for loop tries to grab the next item from the list.

But I've found it's easiest just to create and iterate across a copy of the list so you don't have to worry about it.

foreach(var item in list.ToList())

The added performance overhead of an extra, untouched list is generally negligible compared to the maintainability costs of more complex code.

like image 168
StriplingWarrior Avatar answered Sep 19 '22 07:09

StriplingWarrior


Rather than use a foreach construct, a for loop would allow you to alter the list.

for (var x = 0; x < list.Count; x++) {

}
like image 36
Fosco Avatar answered Sep 19 '22 07:09

Fosco