Friday, November 8, 2019

How to remove elements from a generic list while iterating over it?

You can't use .Remove(element) inside a foreach (var element in X) (because it results in Collection was modified; enumeration operation may not execute. exception)... you also can't use for (int i = 0; i < elements.Count(); i++) and .RemoveAt(i) because it disrupts your current position in the collection relative to i.
You can't use foreach, but you could iterate forwards and manage your loop index variable when you remove an item, like so:
Solution:- 
static void Main(string[] args)
        {
            var s = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

            for (int i = s.Count -1; i >= 0; i--)
            {
                if ((int) Convert.ToChar(s[i])%2 == 1)
                {
                    s.RemoveAt(i);
                }
            }

            Console.ReadKey();
        }

No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...