List Implementation in C# - GeeksforGeeks

02 Sep, 2021
In C#, List is a generic collection which is used to store the elements or objects in the form of a list and it is defined under System.Collection.Generic namespace. It provides the same functionality like ArrayList, but there is only one difference i.e., a list is a generic whereas ArrayList is a non-generic collection. It is dynamic in nature means the size of the list grows, according to the need.
Important Points:
The List class implements the ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IEnumerable, and IList interface.
It can accept null as a valid value for reference types and also allows duplicate elements.
If the Count becomes equal to Capacity, then the capacity of the List increased automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
The elements present in the list are not sorted by default and elements are accessed by zero-based index.
A List class has 3 constructors which are used to create a list and the constructors are as follows:  
List<T>(): This constructor is used to create an instance of the List<T> class that is empty and has the default initial capacity.
List<T>(IEnumerable): This constructor is used to create an instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.
List<T>(Int32): This constructor is used to create an instance of the List<T> class that is empty and has the specified initial capacity.
Let’s see how to create a list using List<T>() constructor:
Step 1: Include System.Collection.Generics namespace in your program with the help of using keyword. 
using System.Collections.Generic;
Step 2: Create a list using List<T> class as shown below: 
List list_name = new List(); 
Step 3: If you want to add elements in your list, then List<T> class provides two different methods and the methods are: 
Add(T): This method is used to add an object to the end of the List<T>. 
AddRange(IEnumerable<T>): This method is used to add the elements of the specified collection to the end of the List<T>.
Note: You can also add elements using collection initializers. As shown below example:
Example: 
// Creating List using List class // and Adding elements using the // Collection initializers List<string> my_list1 = new List<string>() { “geeks”, “Geek123”, “GeeksforGeeks” };  
Step 4: You can access the elements of the list by using the following ways: 
Using foreach loop: You can use foreach loop to access the elements/objects of the List.Example:
// Accessing elements of my_list // Using foreach loop foreach(int a in my_list) { Console.WriteLine(a); }  
Using ForEach() method: This method is used to perform the specified action on each element of the List<T>.Example:
// Accessing elements of my_list // Using ForEach method my_list.ForEach(a = > Console.WriteLine(a));  
Using for loop: You can use for loop to access the elements/objects of the List.Example:
// Accessing elements of my_list // Using for loop for (int a = 0; a < my_list.Count; a++) { Console.WriteLine(my_list[a]); }  
Using indexers: You can use indexers to access the elements/objects of the List.Example:
// Accessing elements of my_list // Using indexers Console.WriteLine(my_list[3]); Console.WriteLine(my_list[4]);  
Example: 
C#
// C# program to illustrate how// to create a listusing System;using System.Collections.Generic; class GFG {     // Main Method    static public void Main()    {         // Creating list using List class        // and List<T>() Constructor        List<int> my_list = new List<int>();         // Adding elements to List        // Using Add() method        my_list.Add(1);        my_list.Add(10);        my_list.Add(100);        my_list.Add(1000);        my_list.Add(10000);        my_list.Add(100000);        my_list.Add(1000000);         // Accessing elements of my_list        // Using foreach loop        foreach(int a in my_list)        {            Console.WriteLine(a);        }    }}
1
10
100
1000
10000
100000
1000000
 
You can remove the elements of the list by using the following methods provided by List<T> class:
Remove(T): This method is used to remove the first occurrence of a specific object from the List.
RemoveAll(Predicate<T>): This method is used to remove all the elements that match the conditions defined by the specified predicate.
RemoveAt(Int32): This method is used to remove the element at the specified index of the List.
RemoveRange(Int32, Int32): This method is used to remove a range of elements from the List<T>.
Clear(): This method is used to remove all elements from the List<T>.
Example:
C#
// C# program to illustrate how// to remove objects from the listusing System;using System.Collections.Generic; class GFG {     // Main Method    static public void Main()    {         // Creating list using List class        // and List<T>() Constructor        List<int> my_list = new List<int>();         // Adding elements to List        // Using Add() method        my_list.Add(1);        my_list.Add(10);        my_list.Add(100);        my_list.Add(1000);        my_list.Add(10000);        my_list.Add(100000);        my_list.Add(1000000);        my_list.Add(10000000);        my_list.Add(100000000);         // Initial count        Console.WriteLine("Initial count:{0}", my_list.Count);         // After using Remove() method        my_list.Remove(10);        Console.WriteLine("2nd count:{0}", my_list.Count);         // After using RemoveAt() method        my_list.RemoveAt(4);        Console.WriteLine("3rd count:{0}", my_list.Count);         // After using RemoveRange() method        my_list.RemoveRange(0, 2);        Console.WriteLine("4th count:{0}", my_list.Count);         // After using Clear() method        my_list.Clear();        Console.WriteLine("5th count:{0}", my_list.Count);    }}
Initial count:9
2nd count:8
3rd count:7
4th count:5
5th count:0
 
You can sort the elements by using Sort() method. This method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
Example: 
C#
// C# program to illustrate how// sort a listusing System;using System.Collections.Generic; class GFG {     // Main Method    static public void Main()    {         // Creating list using List class        // and List<T>() Constructor        List<int> my_list = new List<int>();         // Adding elements to List        // Using Add() method        my_list.Add(496);        my_list.Add(1000);        my_list.Add(100);        my_list.Add(10);        my_list.Add(10000);        my_list.Add(10000000);        my_list.Add(1000000);        my_list.Add(100000);        my_list.Add(0000);         // Without sorted List        Console.WriteLine("UnSorted List:");        foreach(int a in my_list)        {            Console.WriteLine(a);        }         // After Sort method        my_list.Sort();        Console.WriteLine("Sorted List:");        foreach(int a in my_list)        {            Console.WriteLine(a);        }    }}
UnSorted List:
496
1000
100
10
10000
10000000
1000000
100000
0
Sorted List:
0
10
100
496
1000
10000
100000
1000000
10000000
 
nielgp93
rajeev0719singh
CSharp-Generic-List
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
String.Split() Method in C# with Examples
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
C# | Delegates
C# | Arrays of Strings
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1