C# .NET - ArrayList - Asked By Naresh Kumar on 20-Oct-10 08:19 AM


I have one ArrayList() having values like,
I need to remove the items by Index.
Suppose if I give index 1,2 then the ArrayList should remove B,C items.
The Output ArrayList should have A,D,E.

Please suggest me a solution.

Thanks in advance.
Nowshad M replied to Naresh Kumar on 20-Oct-10 08:35 AM

Try the following code

    public static Array RemoveAt(Array source, int index)
if (source == null)
throw new ArgumentNullException("source");

if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");

Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

return dest;

This is used like this:

class Program
static void Main(string[] args)
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
[i] = (i+1).ToString();

string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);

for (int i = 0; i < y.Length; i++)

_ash_ k replied to Naresh Kumar on 20-Oct-10 08:37 AM
You can use the RemoveAt() method of the arraylist to remove an item based on the index. However, remember that the arraylist will change the index values as soon as a value is removed from it.

ArrayList arr = new ArrayList();
arr.RemoveAt(1); //removes the item at index 1 i.e. "a1"
but the new index value of 1 becomes "a2"
so arr.RemoveAt(1); //removes the item at NEW index 1 i.e. "a2"

So, it is rather touch to remove items from an arraylist based on the index value. Intead, you should try using a HashTable which is an arraylist with a key. You can remove an item based on a unique key .... see an example below:

Hashtable hh = new Hashtable();
            hh.Remove(0); //removes the item with key value 1 form the hashtable
            hh.Remove(2); //removes the item with key value 2 form the hashtable

Hope this helps.

Naresh Kumar replied to _ash_ k on 20-Oct-10 09:02 AM
Thanks for your reply,

The values are not unique in the ArrayList, so I can't use Hashtable there.
sri sri replied to Naresh Kumar on 20-Oct-10 09:19 AM

check the below code

for(int i = 0; i <= list.Count - 1; i++)
object o = list[i];
if (o.ToString() == "A")