How to Quickly Remove Items From a List

前端 未结 11 1544
情歌与酒
情歌与酒 2020-11-30 01:45

I am looking for a way to quickly remove items from a C# List. The documentation states that the List.Remove() and List.RemoveAt()<

11条回答
  •  抹茶落季
    2020-11-30 02:05

    If you still want to use a List as an underlying structure, you can use the following extension method, which does the heavy lifting for you.

    using System.Collections.Generic;
    using System.Linq;
    
    namespace Library.Extensions
    {
        public static class ListExtensions
        {
            public static IEnumerable RemoveRange(this List list, IEnumerable range)
            {
                var removed = list.Intersect(range).ToArray();
                if (!removed.Any())
                {
                    return Enumerable.Empty();
                }
    
                var remaining = list.Except(removed).ToArray();
                list.Clear();
                list.AddRange(remaining);
    
                return removed;
            }
        }
    }
    

    A simple stopwatch test gives results in about 200ms for removal. Keep in mind this is not a real benchmark usage.

    public class Program
        {
            static void Main(string[] args)
            {
                var list = Enumerable
                    .Range(0, 500_000)
                    .Select(x => x.ToString())
                    .ToList();
    
                var allFifthItems = list.Where((_, index) => index % 5 == 0).ToArray();
    
                var sw = Stopwatch.StartNew();
                list.RemoveRange(allFifthItems);
                sw.Stop();
    
                var message = $"{allFifthItems.Length} elements removed in {sw.Elapsed}";
                Console.WriteLine(message);
            }
        }
    

    Output:

    100000 elements removed in 00:00:00.2291337

提交回复
热议问题