Why RemoveAll don't remove specific elements from list?

350 Views Asked by At

RemoveAll method don't work when I try to remove all elements. After removing I try to Console.WriteLine() all elements from mainArray using foreach loop. Why this way of removing specific elements from the list don't work and maybe there is better way?

        var mainArray = new int[] { 1, 2, 1 , 2, 3  };

        mainArray.ToList().RemoveAll(n => n == 1);
1

There are 1 best solutions below

0
Klorissz On

Why RemoveAll don't remove specific elements from list?

Short answer: it does.

Long answer: You started with an array. If you hover your mouse over the .ToList() method, you can see the return type. No surprise it is a List<Int32>. A different object, in a different place in your memory. You are removing the elements from the List, and not from the array.

var mainArray = new Int32[] { 1, 2, 1, 2, 3 };
var list = mainArray.ToList();
list.RemoveAll(n => n == 1);
mainArray = list.ToArray();