C# Collection and Iteration
C# has powerful structures for dealing with collections and other data structures. In this blog, we'll be using string formatting and lists. Click on the links if you haven't done them in C# before.
var names = new List<string>
{ "nobita", "bheem", "oggy", "oggy cockroach", "ninja" };
foreach (var name in names)
{
if(name.StartsWith("oggy")) {
Console.WriteLine($"Need to remove {name}!");
names.Remove(name);
}
}
This code tries to remove names starting with "oggy" from a list. Try it in the interactive editor offered by the above tutorial (click 'Enter focus mode' at the bottom of this site)
Does it work? No!
Which is the line that's causing the crash? How would you resolve it?
The line where the foreach loop is used is causing the error and gives the following exception:
ReplyDeleteUnhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
The reason behind this is: " The foreach statement repeats a group of statements for each element in the collection. modifying a collection whilst iterating it using foreach, it uses randomly IEnumerator instance. Hence, the foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects. To resolve this issue, we can use for loop as follows:"
var names = new List { "nobita", "bheem", "oggy", "oggy cockroach", "ninja" };
for(int i=0;i<names.Count;i++)
{
if(names[i].StartsWith("oggy")) {
Console.WriteLine($"Need to remove {names[i]}!");
names.Remove(names[i]);
i=i-1;
}
}