Best practice to avoid InvalidOperationException: Collection was modified?

前端 未结 4 901
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 00:42

Very often I need something like that:

 foreach (Line line in lines)
 {
    if (line.FullfilsCertainConditions())
    {
       lines.Remove(line)
    }
 }
         


        
4条回答
  •  星月不相逢
    2021-02-08 00:52

    This is baked directly into List:

    lines.RemoveAll(line => line.FullfilsCertainConditions());
    

    or in C# 2.0:

    lines.RemoveAll(delegate(Line line) {
        return line.FullfilsCertainConditions();
    });
    

    In the non-List case (your edit to the question), you could wrap this something like below (untested):

    static class CollectionUtils
    {
        public static void RemoveAll(IList list, Predicate predicate)
        {
            int count = list.Count;
            while (count-- > 0)
            {
                if (predicate(list[count])) list.RemoveAt(count);
            }
        }
        public static void RemoveAll(IList list, Predicate predicate)
        {
            int count = list.Count;
            while (count-- > 0)
            {
                if (predicate(list[count])) list.RemoveAt(count);
            }
        }
    }
    
    
    

    Since UIElementCollection implements the (non-generic) IList this should work. And quite conveniently, with C# 3.0 you can add a this before IList / IList and have it as an extension method. The only subtlety is that the parameter to the anon-method will be object, so you'll need to cast it away.

    提交回复
    热议问题