ArrayList Collection C#
ArrayList:
ArrayList is also a type of a collection. This data structure is also built in C#. ArrayList is just like an array which we use in C++ and c programming language. In ArrayList the data items are stored in consecutive memory locations. To explain ArrayList in C# let us consider the following example. Like all the other data structures ArrayList can be used in a c# program by including the library:
Using System.Collection.Generic;
Note: This library should not only be included in your main() but also in each class associated with your program.
- Now make a class of Collection Test.
- include System.collection.generic by.
Using System.Collection.Generic;
Now in the CollectionTest{} type the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public void testArrayList() { ArrayList array = new ArrayList(); //add item // (ArrayList) is basically the data structure which we are using and(array) is an object of (ArrayList). //=new ArrayList(); new shows that a new data structure of type ArrayList() is being created and it will be stored in the instance which is (array). array.Add("laptop"); //Add is basically the built in function in c# which is associated with (ArrayList). Anything typed in the brackets of Add() function will be added in (ArrayList). //get item Console.Write(array[0].ToString()); //The above mentioned line will convert any item you want to add in ArrayList to String by ToString() method. //remove item array.Remove("laptop"); //Remove is basically the built in function in c# which is associated with (ArrayList). Anything typed in the brackets of Remove() function will be removed from (ArrayList). //clear array array.Add("laptop"); array.Add("TV"); array.Add("computer"); array.Clear(); //Clear is basically the built in function in c# which is associated with (ArrayList). Clear() clears the whole ArrayList. } |
Now in main() you will make the instance of your class and call the function
s in in the following way:
CollectionTest test=new CollectionTest();
test. testArrayList();
Another Scenario:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
Int size; String itemName; ArrayList array=new ArrayList(); Public void ADDarrayItem() { Console.WriteLine("Enter the Items you WANT to ADD:"); Console.Read(size); for(int i=0; i<=size; i++) { Console.WriteLine("ENTER the name of item"i+1); Console.Read(itemName); array.Add(itemName); } } Public void REMOVEarrayItem() { Console.WriteLine("ENTER the name of item you WANT to REMOVE:"); Console.Read(itemName); for(int j=0; j<=Size;j++) { myArray.RemoveAt(IndexOf(itemName)); } } |