Click here to Skip to main content
15,941,071 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
How can I remove items from an arraylist inside a loop.
This is what I have but I get index out of range error.
Can you see why please?
C#
String[] fileNames = "aaa, bbb, ccc, ddd, ...";
ArrayList fileNamesArray = new ArrayList(fileNames);

//remove un-necessary files...
for (int i = 0; i < fileNamesArray.Count; i++)
{
	string strFileNameFTP = fileNamesArray[i].ToString().ToLower();

	if (strFileNameFTP == "aaa"
            	|| strFileNameFTP == "bbb"
                || strFileNameFTP == "ddd")
	{
	}
	else
	{
		fileNamesArray.RemoveAt(i);
	}
}
Posted

arkiboys wrote:
String[] fileNames = "aaa, bbb, ccc, ddd, ...";

I suppose you intend
C#
String[] fileNames = {"aaa", "bbb", "ccc", "ddd", /*...,*/ "aaa"};



You should change from
arkiboys wrote:
fileNamesArray.RemoveAt(i);

to
C#
fileNamesArray.RemoveAt(i);
i--;
 
Share this answer
 
Comments
arkiboys 10-Feb-12 7:05am    
Thank you
CPallini 10-Feb-12 7:14am    
You are welcome.
That's Aragon 10-Feb-12 7:20am    
Good solution. 5!
 
Share this answer
 
Comments
arkiboys 10-Feb-12 6:47am    
I am now using remove instead of removeat.
This no longer gives me the index out of range error as I used to get before.
BUT, I still have items in the arraylist which are not "aaa", "bbb", "ccc"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900