The issue here is that you modifying the length of the list while iterating. After you deleted at least one item from changedNums
list, its length is less than the initial 6 (so you get IndexOutOfRangeException
). Also, once you deleted k
-th item, you should decrement k
. I modified your sample code to work as follows:
static void Main()
{
List<int> nums = new List<int>() { 1, 22, 30, 4, 5, 6 };
List<int> changedNums = new List<int>(nums);
var currentLength = changedNums.Count;
for (int k = 0; k < currentLength; k++)
{
if (changedNums[k] >= 21 && changedNums[k] <= 32)
{
changedNums.RemoveAt(k);
--k;
--currentLength;
}
}
Console.WriteLine(string.Join(" ", changedNums));
}
This will print: 1 4 5 6
Edit:
As pointed by @derpirscher and @Jon Skeet in comments, index manipulations can be easily avoided by iterating the array from end to start:
List<int> nums = new List<int>() { 1, 22, 30, 4, 5, 6 };
List<int> changedNums = new List<int>(nums);
for (int k = changedNums.Count - 1; k >= 0 ; k--)
if (changedNums[k] >= 21 && changedNums[k] <= 32)
changedNums.RemoveAt(k);
Console.WriteLine(string.Join(" ", changedNums));
An even easier solution to your problem can be achieved using LINQ:
var changedNums = nums.Where(num => num < 21 || num > 32).ToList();
All the solutions will produce the same result 1 4 5 6
2
solved What causes IndexOutOfRangeException here? [closed]