IT Story/C# & WPF

How to use C# ArrayList Class

Hoyami7 2019. 12. 5. 10:38
반응형

ArrayList is one of the most flexible data structure from CSharp Collections. ArrayList contains a simple list of values. ArrayList implements the IList interface using an array and very easily we can add , insert , delete , view etc. It is very flexible because we can add without any size information , that is it will grow dynamically and also shrink.

 

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      ArrayList arrList = new ArrayList();
      arrList.Add("North");
      arrList.Add("East");
      arrList.Add("West");
      arrList.Add("South");
      Console.WriteLine("ArrayList Elements");
      foreach (object item in arrList)
      {
          Console.WriteLine(item);
      }
      Console.ReadKey();
    }
  }
}

Elements can be added or removed from the C# ArrayList collection at any point in time. ArrayList.Insert(Int32, Object) method inserts an element into the ArrayList at the specified index.

 

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      ArrayList arrList = new ArrayList();
      arrList.Add("North");
      arrList.Add("West");
      arrList.Add("South");
      Console.WriteLine("ArrayList Elements...");
      foreach (object item in arrList)
      {
          Console.WriteLine(item);
      }
      //insert an item at the top of arraylist
      arrList.Insert(0, "Directions");
      //insert an item at the 3rd position  of arraylist
      arrList.Insert(2, "East");
      Console.WriteLine("ArrayList Elements after insert...");
      foreach (object item in arrList)
      {
          Console.WriteLine(item);
      }
      Console.ReadKey();
    }
  }
}

Arraylist remove() method removes the first occurrence of a specific object from the ArrayList.

 

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      ArrayList arrList = new ArrayList();
      arrList.Add("North");
      arrList.Add("East");
      arrList.Add("West");
      arrList.Add("South");
      Console.WriteLine("ArrayList Elements...");
      foreach (object item in arrList)
      {
          Console.WriteLine(item);
      }
      //remove() method removes the first occurrence
      arrList.Remove("West");
      Console.WriteLine("ArrayList Elements after remove()...");
      foreach (object item in arrList)
      {
          Console.WriteLine(item);
      }
      Console.ReadKey();
    }
  }
}
반응형