What is the best way to modify a list in a 'foreach' loop?

前端 未结 11 896
不思量自难忘°
不思量自难忘° 2020-11-22 05:23

A new feature in C# / .NET 4.0 is that you can change your enumerable in a foreach without getting the exception. See Paul Jackson\'s blog entry An Interest

11条回答
  •  暖寄归人
    2020-11-22 05:57

    Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList members and aggregate the source list):

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApplication3
    {
        public class ModifiableList : List
        {
            private readonly IList pendingAdditions = new List();
            private int activeEnumerators = 0;
    
            public ModifiableList(IEnumerable collection) : base(collection)
            {
            }
    
            public ModifiableList()
            {
            }
    
            public new void Add(T t)
            {
                if(activeEnumerators == 0)
                    base.Add(t);
                else
                    pendingAdditions.Add(t);
            }
    
            public new IEnumerator GetEnumerator()
            {
                ++activeEnumerators;
    
                foreach(T t in ((IList)this))
                    yield return t;
    
                --activeEnumerators;
    
                AddRange(pendingAdditions);
                pendingAdditions.Clear();
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                ModifiableList ints = new ModifiableList(new int[] { 2, 4, 6, 8 });
    
                foreach(int i in ints)
                    ints.Add(i * 2);
    
                foreach(int i in ints)
                    Console.WriteLine(i * 2);
            }
        }
    }
    

提交回复
热议问题