RemoveAll的高效删除

        static List<int> CalInts(int len=100000)
        {
            List<int> a = Enumerable.Range(0,len).ToList();
            return a;
        }
  List<int> aa = CalInts();
  Stopwatch sw = new Stopwatch();
  sw.Start();
  for(int i = 0; i < aa.Count; i++)
  {
      if (aa[i] % 2 == 0)
      {
          aa.RemoveAt(i);
          i--;
      }
  }
  sw.Stop();
  Console.WriteLine($"hand:{sw.ElapsedMilliseconds}");
  aa = CalInts();
  sw.Restart();
  aa.RemoveAll(n=>n%2==0);
  sw.Stop();
  Console.WriteLine($"removeAll:{sw.ElapsedMilliseconds}");

image

posted @ 2025-08-04 17:26  JohnYang819  阅读(8)  评论(0)    收藏  举报