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

前端 未结 27 2414
忘了有多久
忘了有多久 2020-11-21 22:48

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from

27条回答
  •  遥遥无期
    2020-11-21 23:36

    Using the ToArray() on a generic list allows you to do a Remove(item) on your generic List:

            List strings = new List() { "a", "b", "c", "d" };
            foreach (string s in strings.ToArray())
            {
                if (s == "b")
                    strings.Remove(s);
            }
    

提交回复
热议问题