In C#, a List is a generic collection used to store the elements or objects in the form of a list defined under System.Collections.Generic namespace. It provides the same functionality as ArrayList, the difference is a list is generic whereas ArrayList is a non-generic collection. It is dynamic means the size of the list grows, according to the need.
- 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 increases 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.
Example:
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
List<string> l = new List<string> { "C#", "Java", "Javascript" };
foreach (string name in l)
{
Console.WriteLine(name);
}
}
}
Output
C# Java Javascript
Creating List Using Constructors
The list class has 3 constructors which are used to create a list 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.
Example:
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// default constructor creates an empty list
List<int> list = new List<int>();
list.Add(10);
list.Add(20);
Console.WriteLine("Default Constructor: ");
foreach (var item in list)
{
Console.WriteLine(item);
}
// Constructor from IEnumerable
int[] num = { 10, 20 };
List<int> enumerableList = new List<int>(num);
Console.WriteLine("Constructor with IEnumerable: ");
foreach (var item in enumerableList)
{
Console.WriteLine(item);
}
// Constructor with Initial Capacity
List<int> Clist = new List<int>(2);
Clist.Add(10);
Clist.Add(20);
Console.WriteLine("Constructor with Initial Capacity: ");
foreach (var item in Clist)
{
Console.WriteLine(item);
}
}
}
Output
Default Constructor: 10 20 Constructor with IEnumerable: 10 20 Constructor with Initial Capacity: 10 20
Steps to Create a List
Step 1: Including System.Collections.Generics namespace.
using System.Collections.Generic;
Step 2: Create a list using the List<T> class.
List<T> list_name = new List<T>();
Performing Different Operations on List
1. Adding Elements
For adding elements list, The List<T> class provides two different methods which 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>.
// Add element using Add method
list.Add(1);
list.Add(2);// Adding elements using the
// Collection initializers
List<string> my_list1 = new List<string>() { “geeks”, “Geek123”, “GeeksforGeeks” };
2. Accessing List
We can access the elements of the list by using the following ways:
foreach loop: We can use a foreach loop to access the elements/objects of the List.
// Accessing elements of my_list
// Using foreach loop
foreach(int a in my_list)
{
Console.WriteLine(a);
}
ForEach loop: It is used to perform the specified action on each element of the List<T>.
// Accessing elements of my_list
// Using ForEach method
my_list.ForEach(a = > Console.WriteLine(a));
for loop: We can use a for loop to access the elements/objects of the List.
// Accessing elements of my_list
// Using for loop
for (int a = 0; a < my_list.Count; a++)
{
Console.WriteLine(my_list[a]);
}
Indexers: Indexers used to access the elements/objects of the List.
// Accessing elements of my_list
// Using indexers
Console.WriteLine(my_list[3]);
Console.WriteLine(my_list[4]);
Example:
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// Creating a list of integers
List<int> my_list = new List<int> { 10, 20, 30,};
// Accessing elements using foreach loop
Console.WriteLine("Accessing elements using foreach loop:");
foreach (int a in my_list)
{
Console.WriteLine(a);
}
// Accessing elements using ForEach method
Console.WriteLine("Accessing elements using ForEach method:");
my_list.ForEach(a => Console.WriteLine(a));
// Accessing elements using for loop
Console.WriteLine("Accessing elements using for loop:");
for (int i = 0; i < my_list.Count; i++)
Console.WriteLine(my_list[i]);
// Accessing elements using indexers
Console.WriteLine("Accessing elements using indexers:");
Console.WriteLine($"Element at index 2: {my_list[2]}");
}
}
Output
Accessing elements using foreach loop: 10 20 30 Accessing elements using ForEach method: 10 20 30 Accessing elements using for loop: 10 20 30 Accessing elements using indexers: Element at index 2: 30
3. Remove Elements from the List
- 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:
using System;
using System.Collections.Generic;
class Geeks
{
static public void Main()
{
// Creating list using List class
// and List<T>() Constructor
List<int> l = new List<int>();
// Adding elements to List
// Using Add() method
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
l.Add(5);
// Initial count
Console.WriteLine("Initial count:{0}", l.Count);
l.Remove(3);
Console.WriteLine("after removing 3");
Console.WriteLine("2nd count:{0}", l.Count);
l.RemoveAt(3);
Console.WriteLine("after removing at 3th index");
Console.WriteLine("3rd count:{0}", l.Count);
l.RemoveRange(0, 2);
Console.WriteLine("after removing range from 0 to 2");
Console.WriteLine("4th count:{0}", l.Count);
l.Clear();
Console.WriteLine("after removing all elements");
Console.WriteLine("5th count:{0}", l.Count);
}
}
Output
Initial count:5 after removing 3 2nd count:4 after removing at 3th index 3rd count:3 after removing range from 0 to 2 4th count:1 after removing all elements 5th count:0
4. Sorting a List
We can sort the elements by using the Sort() method. 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:
using System;
using System.Collections.Generic;
class Geeks {
static public void Main()
{
// Creating list using List class
// and List<T>() Constructor
List<int> l = new List<int>();
// Adding elements to List
// Using Add() method
l.Add(2);
l.Add(1);
l.Add(5);
l.Add(3);
l.Add(50);
// Without sorted List
Console.WriteLine("UnSorted List:");
foreach(int a in l) Console.Write(a + ", ");
Console.WriteLine();
// using sort method
l.Sort();
Console.WriteLine("Sorted List:");
foreach(int a in l) Console.Write(a + ", ");
}
}
Output
UnSorted List: 2, 1, 5, 3, 50, Sorted List: 1, 2, 3, 5, 50,
Ways to Implement List
- List<T>: Generic list supporting dynamic storage, indexing, sorting, and searching.
- LinkedList<T>: Doubly linked list with fast insertions/removals but slower indexing.
- Array: Fixed-size structure, less flexible and costly to resize.
- Custom List: User-defined list for specific needs and flexibility.