Friday, April 23, 2021

C# ArrayList Methods

ArrayList is a non generic collection. Its items are stored as objects in the ArrayList. The boxing and unboxing occurs which is the overhead in such kind of non-generic collections.


using System;
using System.Collections;

/*
 * ArrayList members: Add, Capacity, Contains, Clear, Count
 * AddRange, GetRange, SetRange, InsertRange, IndexOf, LastIndexOf, Insert, Sort, Reverse, ToArray 
 */

namespace Console_ArrayListMembers
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create ArrayList
            ArrayList arrlist = new ArrayList();
            //Add individual heterogeneous items 
            arrlist.Add(9);
            arrlist.Add("Ajeet");
            arrlist.Add(true);
            arrlist.AddRange(new int[] { 1, 4, 2, 5 });
            string[] colors = new string[] { "pink", "red", "blue" };
            arrlist.AddRange(colors);
            Console.WriteLine();
            Console.Write("\nAdded items are: ");
            foreach (var item in arrlist)
            {
                Console.Write( item + " ");
            }
            Console.WriteLine();
            //Console.WriteLine("\nAfter removing colors:---");
            //arrlist.Remove(colors);//issue ??
            arrlist.Remove("Ajeet");
            Console.Write("\nAfter removing Ajeet and then 4 elements starting with index 2: ");
            arrlist.RemoveRange(2, 4); //remove 4 elements, range of elements starting with index 2
            foreach (var item in arrlist)
            {
                Console.Write(item +" ");
            }
            Console.Write("\nList after removing an item at index 2: ");
            arrlist.RemoveAt(2);
            foreach (var item in arrlist)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine("\nCapacity: {0}", arrlist.Capacity);// returns current capacity
            Console.WriteLine("Count: {0}",arrlist.Count);//returns avaialble number of items
            Console.WriteLine("Contains Ajeet: {0}",arrlist.Contains("Ajeet"));// returns boolean
            ArrayList arrlist2 = arrlist.GetRange(1, 3); //returns an arraylist
            Console.Write("GetRange(1, 3): ");
            foreach (var item in arrlist2)
            {
                Console.Write(item + " ");
            }
            Console.Write("\nIndexOf(blue): ");
            Console.WriteLine(arrlist.IndexOf("blue"));
            Console.Write("LastIndexOf(blue): ");
            Console.WriteLine(arrlist.LastIndexOf("blue"));
        }
    }
}



OUTPUT

Added items are: 9 Ajeet True 1 4 2 5 pink red blue

After removing Ajeet and then 4 elements starting with index 2: 9 True pink red blue
List after removing an item at index 2: 9 True red blue
Capacity: 16
Count: 4
Contains Ajeet: False
GetRange(1, 3): True red blue
IndexOf(blue): 3
LastIndexOf(blue): 3

No comments:

Post a Comment

Hot Topics