Intelligent way of removing items from a List while enumerating in C#

后端 未结 10 543
闹比i
闹比i 2020-11-29 19:05

I have the classic case of trying to remove an item from a collection while enumerating it in a loop:

List myIntCollection = new List()         


        
10条回答
  •  失恋的感觉
    2020-11-29 19:42

    For those it may help, I wrote this Extension method to remove items matching the predicate and return the list of removed items.

        public static IList RemoveAllKeepRemoved(this IList source, Predicate predicate)
        {
            IList removed = new List();
            for (int i = source.Count - 1; i >= 0; i--)
            {
                T item = source[i];
                if (predicate(item))
                {
                    removed.Add(item);
                    source.RemoveAt(i);
                }
            }
            return removed;
        }
    

提交回复
热议问题