ArrayList in C#.




In this post, I'll show you How to use the C# ArrayList Object Class. I tried to use as many Properties and Methods the ArrayList Class has to offer as possible.


The ArrayList Object resides in the System.Collections namespace, that is why you must include that namespace in the class that will use it. You achieve this by adding:

using System.Collections;
 



using System;
using System.Linq;
using System.Text;
using System.Collections;
namespace ArratsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("********* BEGIN OF APROACH 1 ******)\n");

            ArrayList aList = new ArrayList();
            //ADD ELEMENTS MANUALLY
            aList.Add("ONE");
            aList.Add("TWO");
            aList.Add("THREE");
            aList.Add("FOUR");
            aList.Add("FIVE");
            aList.Add("SIX");
            aList.Add("SEVEN");

            //ROMOVE BY OBJECT MATCH
            aList.Remove("THREE");
            //ROMOVE BY OBJECT INDEX (ZERO BASED INDEX)
            aList.RemoveAt(0);
            //REPLACE "SIX" WITH "6"
            aList[3] = "6";

            //ITERATES OVER THE LISTLIST
            foreach(string str in aList)
            {
                //PRINTS OUT EACH ELEMENT
                Console.WriteLine(str);
            }

            Console.WriteLine("\n********* END OF APROACH 1 *********)\n\n" +
                              "********* BEGIN OF APROACH 2 *******");
                              
            //ANOTHER APROACH
            //CLEAR THE LIST (GARBAGE COLLECTOR IS CALLED
            aList.Clear();

            //INITIALIZE aList WITH 4 VALUES.
            aList = new ArrayList(){"Mauricio","Lucia","Peter","Jhon"};

            //ORDER ALPHABETICALLY (if no IComarer was defined)
            aList.Sort();

            //PRINTS THE QUANTITY OF ITEMS STORED IN THE LIST
            Console.WriteLine("\nNUMBER OF ITEMS: "+aList.Count+"\n");

            //ITERATES OVER THE ARRAYLIST
            foreach (string str in aList)
            {
                //PRINTS OUT EACH ELEMENT
                Console.WriteLine(str);
            }
            Console.WriteLine("\n********* END OF APROACH 2 *********");

            //END MESSAGE
            Console.WriteLine("\n\nPRESS ANY KEY TO QUIT");
            Console.ReadKey();
        }
    }
}



No comments:

Post a Comment

2 ads