Search:
Welcome Guest | Register | Login
logo

Remove item from an array in for loop error index out of range

I am using for loop and match some condition, if condition match, remove the item from the array but at the end I am getting out of range error, here is my code

  ArrayList arr = new ArrayList { 1, 2, 3, 4, 5, 6, 7, 8, 9 ... 100};
        for (int i = 0; i < arr.Count; i++)
            if (Convert.ToInt32(arr[i]) % 5 == 0)
                arr.RemoveAt(i);

How to fix this issue?

  • ASP.Net
  • Array
1
 
Asked: 05 Mar 2013
Reputation: 25
Alonzo Carr
2 Answers

In you given code total items are 100, and you try to loop from 0 to 99 but you remove those items which are divisible by 5 so array length become less than 100 that's why you are getting error.

Simplest solution of this problem is to loop in reverse order (from last to first) and it will work,

   for (int i = arr.Count; i >= 0; i--)
        if (Convert.ToInt32(arr[i]) % 5 == 0)
            arr.RemoveAt(i);
1
 
Answered: 06 Mar 2013
Reputation: 1,880
Hamden

Simply you can get a list where item not divisible by 5

Int32[] resultArray = arr.Where(x=>x.% 5 != 0)
0
 
Answered: 11 Mar 2013
Reputation: 296
Jason Olivera
Login to post your answer