ArrayList
The ArrayList class is very useful if you are working with arrays and need to add, remove, index, or search for data in a collection. An ArrayList can also have values of different types stored in a sequential manner and the values can be added or removed as per the need.
Methods
Some of the common methods of ArrayList are as follows,
- Add (Add an item in an ArrayList)
Syntax : ArrayList.add(object)
- Insert (Insert an item in a specified position in an ArrayList)
Syntax : ArrayList.insert(index,object)
- Remove (Remove an item from ArrayList)
Syntax : ArrayList.Remove(object)
- RemoveAt (Remove an item from specified position)
ArrayList.RemoveAt(index)
- Sort (Sort items in an ArrayList)
ArrayList.Sort()
Example
- using System;
- using System.Collections.Generic;
- using System.Collections;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace ArrayListTest
- {
- class Program
- {
- static void Main(string[] args)
- {
- ArrayList itemList = new ArrayList();
- itemList.Add("Item4");
- itemList.Add("Item5");
- itemList.Add("Item2");
- itemList.Add("Item1");
- itemList.Add("Item3");
- Console.WriteLine("\n\tShows Added Items in ArrayList\n");
- for (int i = 0; i <itemList.Count; i++)
- {
- Console.WriteLine("\t"+itemList[i].ToString());
- }
- itemList.Insert(3, "Item6");
- itemList.Sort();
- itemList.Remove("Item1");
- itemList.RemoveAt(3);
-
- Console.WriteLine("\n\tShows Final items in ArrayList\n");
- for (int i = 0; i < itemList.Count; i++)
- {
- Console.WriteLine("\t"+itemList[i].ToString());
- }
- Console.Read();
- }
- }
- }
OUTPUT