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

Hi ALL,

I have one ArrayList() having values like,
A
B
C
D
E
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
Hi,

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++)
            x
[i] = (i+1).ToString();

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

       
for (int i = 0; i < y.Length; i++)
           
Console.WriteLine(y[i]);
   
}
}

Thanks,
Nowshad
_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.Add("a0");
            arr.Add("a1");
            arr.Add("a2");
            arr.Add("a3");
            arr.Add("a4");
            arr.Add("a5");
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.Add(0,"a0");
            hh.Add(1,"a1");
            hh.Add(2,"a2");
            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.

_ash_
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
hi,

check the below code

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