List Collection Class in C#

Introduction

A List is one of the generic collection classes in the "System.Collection.Generic" namespace. There are several generic collection classes in the System.Collection.Generic namespace that includes the following:

  1. Dictionary
  2. List
  3. Stack
  4. Queue

A List class can be used to create a collection of any type. For example, we can create a list of Integers, strings and even any complex types.

Why to use a List

  1. Unlike arrays, a List can grow in size automatically in other words a list can be re-sized dynamically but arrays cannot.

  2. List is a generic type.

  3. The List class also provides methods to search, sort and manipulate lists.

Example 1: Using Array.

I am taking an example to store data in an array and see what the problem is in storing the data in the array.

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace List_Methods_Properties  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             customer customer1 = new customer()  
  11.             {  
  12.                 EmpID = 1,  
  13.                 EmpName = "Sourabh",  
  14.                 EmpSalary = 50000  
  15.             };  
  16.             customer customer2 = new customer()  
  17.             {  
  18.                 EmpID = 2,  
  19.                 EmpName = "Shaili",  
  20.                 EmpSalary = 60000  
  21.             };  
  22.             customer customer3 = new customer()  
  23.             {  
  24.                 EmpID = 3,  
  25.                 EmpName = "Saloni",  
  26.                 EmpSalary = 55000  
  27.             };  
  28.             //Customer array
  29.             customer[] customers = new customer[2];  
  30.             customers[0] = customer1;  
  31.             customers[1] = customer2;  
  32.   
  33.             //here I am adding one more cutomer to customers array and building the programs  
  34.             customers[2] = customer3;  
  35.         }  
  36.     }  
  37.     class customer  
  38.     {  
  39.         public int EmpID { getset; }  
  40.         public string EmpName { getset; }  
  41.         public int EmpSalary { getset; }  
  42.   
  43.     }  
  44. }  
In the example above I have created one class named "customer" and In the main method I have created an array named customers with a size of two. When I build this program (using CTRL+SHIFT+B) then I will get output like built successfully but when I run this program then I get the error: 
 
 
 
When I run this program then at run time I will get the exception index was out of the bound of the array.

 
 
 
 
 
So now we use List: A list is a generic data type that can hold any type of data that may be integer, float, string or may be complex type. To create a list we have 3 types of constructors.
  1. List<Type> Customers = new List<Type>();//default constructor  
  2. List<Type> Customers = new List<Type>(int capacity);//with spacific capacity
  3. List<Type> Customers = new List(IEnumerable<Type> collection);//with spacific collection  

Example 2: Using List.

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace List_Methods_Properties  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             customer customer1 = new customer()  
  11.             {  
  12.                 EmpID = 1,  
  13.                 EmpName = "Sourabh",  
  14.                 EmpSalary = 50000  
  15.             };  
  16.             customer customer2 = new customer()  
  17.             {  
  18.                 EmpID = 2,  
  19.                 EmpName = "Shaili",  
  20.                 EmpSalary = 60000  
  21.             };  
  22.             customer customer3 = new customer()  
  23.             {  
  24.                 EmpID = 3,  
  25.                 EmpName = "Saloni",  
  26.                 EmpSalary = 55000  
  27.             };  
  28.   
  29.             //using list  
  30.             // Creating List with initial capacity 2  
  31.             List<customer> Customers = new List<customer>(2);  
  32.             Customers.Add(customer1);  // Here Add Method is used to add the item to the list
  33.             Customers.Add(customer2);  
  34.   
  35.             //adding one more customer wheather capacity is 2 only  
  36.             Customers.Add(customer3);  
  37.         }  
  38.     }  
  39.     class customer  
  40.     {  
  41.         public int EmpID { getset; }  
  42.         public string EmpName { getset; }  
  43.         public int EmpSalary { getset; }  
  44.   
  45.     }  
  46. }  
Output
 
In the preceding example we are adding 3 items to the list wereas the capacity is only two so it proves that a List can be automatically re-sized.

Add Method: Add method is used to add the items to the list.

How to access items from the List: To add the item to the list we use an index number to access it.
  1. // <List Item>[index number]  
   Code:
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace List_Methods_Properties  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             customer customer1 = new customer()  
  11.             {  
  12.                 EmpID = 1,  
  13.                 EmpName = "Sourabh",  
  14.                 EmpSalary = 50000  
  15.             };  
  16.             customer customer2 = new customer()  
  17.             {  
  18.                 EmpID = 2,  
  19.                 EmpName = "Shaili",  
  20.                 EmpSalary = 60000  
  21.             };  
  22.             customer customer3 = new customer()  
  23.             {  
  24.                 EmpID = 3,  
  25.                 EmpName = "Saloni",  
  26.                 EmpSalary = 55000  
  27.             };  
  28.   
  29.             //using list  
  30.             // Creating List with initial capacity 2  
  31.             List<customer> Customers = new List<customer>(2);  
  32.             Customers.Add(customer1);  
  33.             Customers.Add(customer2);  
  34.             Customers.Add(customer3);  
  35.   
  36.             //Accessing Item from the List  
  37.   
  38.             customer c1 = Customers[0];  
  39.             Console.WriteLine("ID={0}, Name={1}, Salary={2}",c1.EmpID,c1.EmpName,c1.EmpSalary);  
  40.   
  41.             customer c2 = Customers[1];  
  42.             Console.WriteLine("ID={0}, Name={1}, Salary={2}", c2.EmpID, c2.EmpName, c2.EmpSalary);  
  43.   
  44.             customer c3 = Customers[2];  
  45.             Console.WriteLine("ID={0}, Name={1}, Salary={2}", c3.EmpID, c3.EmpName, c3.EmpSalary);  
  46.         }  
  47.     }  
  48.     class customer  
  49.     {  
  50.         public int EmpID { getset; }  
  51.         public string EmpName { getset; }  
  52.         public int EmpSalary { getset; }  
  53.   
  54.     }  
  55. }  
 How to access all the items of the list using foreach loop:
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace List_Methods_Properties  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             customer customer1 = new customer()  
  11.             {  
  12.                 EmpID = 1,  
  13.                 EmpName = "Sourabh",  
  14.                 EmpSalary = 50000  
  15.             };  
  16.             customer customer2 = new customer()  
  17.             {  
  18.                 EmpID = 2,  
  19.                 EmpName = "Shaili",  
  20.                 EmpSalary = 60000  
  21.             };  
  22.             customer customer3 = new customer()  
  23.             {  
  24.                 EmpID = 3,  
  25.                 EmpName = "Saloni",  
  26.                 EmpSalary = 55000  
  27.             };  
  28.   
  29.             //using list  
  30.             // Creating List with initial capacity 2  
  31.             List<customer> Customers = new List<customer>(2);  
  32.             Customers.Add(customer1);  
  33.             Customers.Add(customer2);  
  34.             Customers.Add(customer3);  
  35.   
  36.             //Accessing Item from the List using for loop  
  37.   
  38.             foreach (customer c in Customers)  
  39.             {  
  40.                 Console.WriteLine("ID={0}, Name={1}, Salary={2}", c.EmpID, c.EmpName, c.EmpSalary);  
  41.             }  
  42.         }  
  43.     }  
  44.     class customer  
  45.     {  
  46.         public int EmpID { getset; }  
  47.         public string EmpName { getset; }  
  48.         public int EmpSalary { getset; }  
  49.     }  
  50. }  
Output

   

Note: You can also use for or while loop to access all the items.

Different Properties of a "List":

  1. Count: This property is the number of items of the List.

  2. Capacity: This property is the capacity of the List. By default the capacity is 0, then starts with 4, 8, 16, 32.....
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace List_Methods_Properties  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             List<string> Names = new List<string>();  
  11.             Names.Add("Sourabh");  
  12.             Names.Add("Shaili");  
  13.             Names.Add("Saloni");  
  14.             Console.WriteLine("Number of Items in the List is:" + Names.Count);  
  15.             Console.WriteLine("Capacity of the List is:" + Names.Capacity);  
  16.         }  
  17.     }  
  18. }  
Output

  

 Different Methods of a "List":

  1. Contains: This method determines whether or not an element is in the List, if the element is present in the List then this method returns "True" else "False".

  2. Insert: This method is used to insert an element at a specific index.

  3. Remove: This method removes the first occurrence of the specific object from the list.

  4. RemoveAll: This method removes all the elements that matches the condition.

  5. RemoveAt: This method remove the element from the specified index.

  6. Clear: Removes all the element from the list.

  7. Sort: This method is used sort the List

  8. Reverse: This method reverses the order of the elements in the entire List.

  9. TrimExcess: This method sets the capacity to the actual number of elements in the list.

Example:

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace List_Methods_Properties  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             List<string> Names = new List<string>();  
  11.             Names.Add("Sourabh");  
  12.             Names.Add("Shaili");  
  13.             Names.Add("Saloni");  
  14.             Names.Add("Ankit");  
  15.             Names.Add("Bill");  
  16.             Names.Add("Dinesh");  
  17.             Names.Add("Mahesh Chand");  
  18.             Names.Add("DJ");  
  19.             Names.Add("Rajesh");  
  20.             Names.Add("Rajesh");  
  21.             Names.Add("Rajesh");  
  22.             //Contains: This method determines that weather the element is in List or not,   
  23.             //If element is present in List then this method returns "True" else return "False".   
  24.             Console.WriteLine(Names.Contains("Sourabh\n"));  
  25.   
  26.             //accessing all the element from the list  
  27.             foreach (string Name in Names)  
  28.             {  
  29.                 Console.WriteLine(Name);  
  30.             }  
  31.               
  32.             //Insert: This method is used to insert an element in particular index.  
  33.             Names.Insert(5, "Rajesh");  
  34.   
  35.             Console.WriteLine("\n\nAfter Inserting Rajesh at 5th index");  
  36.             foreach (string Name in Names)  
  37.             {  
  38.                 Console.WriteLine(Name);  
  39.             }  
  40.   
  41.             //Sort: Sorts the List  
  42.             Names.Sort();  
  43.             Console.WriteLine("\n\nSorting in List");  
  44.             foreach (string Name in Names)  
  45.             {  
  46.                 Console.WriteLine(Name);  
  47.             }  
  48.   
  49.             //Reverse: Reverse the order of the element of List  
  50.             Names.Reverse();  
  51.             Console.WriteLine("\n\nReverse Elements of List");  
  52.             foreach (string Name in Names)  
  53.             {  
  54.                 Console.WriteLine(Name);  
  55.             }  
  56.   
  57.             //Remove: Removes the elements from the list              
  58.             Names.Remove("Rajesh");  
  59.             Console.WriteLine("\n\nRemove Element from the List using Remove Method");  
  60.             foreach (string Name in Names)  
  61.             {  
  62.                 Console.WriteLine(Name);  
  63.             }  
  64.   
  65.             //RemoveAt:Remove the elements from the list at the specific index  
  66.             Names.RemoveAt(7);  
  67.             Console.WriteLine("\n\nRemove Element from the List using RemoveAt Method");  
  68.             foreach (string Name in Names)  
  69.             {  
  70.                 Console.WriteLine(Name);  
  71.             }  
  72.   
  73.             //nTrimExcess:Sets the capacity to the actual number of elements in the List  
  74.             Names.TrimExcess();  
  75.             Console.WriteLine("\n\nTrimExcess Method");  
  76.             Console.WriteLine("Capacity: {0}", Names.Capacity);  
  77.             Console.WriteLine("Count: {0}", Names.Count);  
  78.   
  79.   
  80.             //Clear:Removes all elements from the List  
  81.             Names.Clear();  
  82.             Console.WriteLine("\n\nClear Method");  
  83.             Console.WriteLine("Capacity: {0}", Names.Capacity);  
  84.             Console.WriteLine("Count: {0}", Names.Count);  
  85.             Console.ReadKey();  
  86.         }  
  87.     }  
  88. }  
Output

  

Up Next
    Ebook Download
    View all
    Learn
    View all
    sourabhsomani.com