Answers for "How to Insert or Delete Elements to Collection During Iteration in c#"

C#
1

How to Insert or Delete Elements to Collection During Iteration in c#

// one of many possibilities is to use another collection
// for other possibilities see: 
//https://www.techiedelight.com/remove-elements-from-list-while-iterating-csharp/
// or: 
// https://stackoverflow.com/questions/1582285/how-to-remove-elements-from-a-generic-list-while-iterating-over-it
// https://stackoverflow.com/questions/16497028/how-add-or-remove-object-while-iterating-collection-in-c-sharp/16497068

using System;
using System.Collections.Generic;
using System.Linq;
 
public class Example
{
    public static void Main()
    {
        List<int> list = new List<int>(Enumerable.Range(1, 10));
        HashSet<int> toRemove = new HashSet<int>();
 
        foreach (int item in list)
        {
            if (item % 2 == 0)      // remove even elements
            {
                toRemove.Add(item);
            }
        }
 
        list.RemoveAll(toRemove.Contains);
        Console.WriteLine(String.Join(',', list));
    }
}
Posted by: Guest on March-12-2021

Code answers related to "How to Insert or Delete Elements to Collection During Iteration in c#"

C# Answers by Framework

Browse Popular Code Answers by Language