Generic List Collection in C#

Generic List<T> Collection Class in C# with Examples

In this article, I am going to discuss the Generic List<T> Collection Class in C# with Examples. Please read our previous article where we discussed How to implement Generics in C# with Examples. The Generic List<T> Class in C# is a collection class that is present in System.Collections.Generic namespace. The List Collection class is one of the most widely used generic collection classes in real-time applications. At the end of this article, you will understand the following pointers with Examples.

  1. What is Generic List<T> Collection in C#?
  2. How to Create a List in C#?
  3. How to Add Elements into a Generic List<T> Collection in C#?
  4. How to Access a Generic List<T> Collection in C#?
  5. How to Insert Elements at a Specific Position in a C# List?
  6. How to Check the Availability of an Element in a List Collection in C#?
  7. How to Remove Elements from a Generic List Collection in C#?
  8. How to Copy an Array to a List in C#?
  9. Generic List Collection with Complex Type in C#
  10. How to Find Element in a Generic List Collection in C#?
  11. How to Sort a List of Simple Type and Complex Type in C#?
What is Generic List<T> Collection in C#?

The Generic List<T> Class in C# is a collection class that is present in System.Collections.Generic namespace. This Generic List<T> Collection Class represents a strongly typed list of objects which can be accessed by using the index. It also provides methods that can be used for searching, sorting, and manipulating the list items.

We can create a collection of any data type by using the generic list class in C#. For example, if we want then we can create a list of strings, a list of integers, and even though it is also possible to create a list of the user-defined complex type such as a list of customers, a list of products, etc. The most important point that you need to keep in mind is the size of the collection grows automatically when we add items to the collection.

How to Create a List in C#?

The Generic List Collection Class in C# provides the following constructors which we can use to create an instance of the List collection class.

  1. List(): This constructor is used to initialize a new instance of the Generic List class that is empty and has the default initial capacity.
  2. List(IEnumerable<T> collection): This constructor is used to initialize a new instance of the Generic List class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied. The parameter collection specifies the collection whose elements are copied to the new list.
  3. List(int capacity): This constructor is used to initialize a new instance of the Generic List class that is empty and has the specified initial capacity. The parameter capacity specifies the number of elements that the new list can initially store.

Let’s see how to create a List<T> collection using the List() constructor in C#:

Step1:
As the List<T> Collection Class belongs to System.Collections.Generic namespace, so first, we need to include the System.Collections.Generic namespace into our program as follows:
using System.Collections.Generic;

Step2:
Next, we need to create an instance of the List<T> collection class using the List() constructor as follows. Here Type can be any built-in data type such as int, string, double, etc., or user-defined data type like Customer, Product, Employee, etc.
List<Type> listName = new List<Type>();

How to Add Elements into a Generic List<T> Collection in C#?

If you want to add elements to the generic list collection then you need to use the following Add() and AddRange() method of the Generic List Collection Class in C#.

  1. Add(T item): The Add(T item) method is used to add an element to the end of the Generic List. Here, the parameter item specifies the object to be added to the end of the Generic List. The value can be null for a reference type.
  2. AddRange(IEnumerable<T> collection): The AddRange(IEnumerable<T> collection) method is used to add the elements of the specified collection to the end of the Generic List. The parameter collection specifies the collection whose elements should be added to the end of the Generic List. The collection itself cannot be null, but it can contain elements that are null if type T is a reference type.

For example, Adding Elements using Add Method of the List Class:
List<string> countries = new List<string>();
countries.Add(“India”);
countries.Add(“Srilanka”);

Adding Elements using the AddRange Method of the List Class. In this case, we have two collections and we need to add one collection into another collection as follows.
List<string> countries = new List<string>();
countries.Add(“India”);
countries.Add(“Srilanka”);

List<string> newCountries = new List<string>();
newCountries.Add(“USA”);
newCountries.Add(“UK”);

countries.AddRange(newCountries);

Even it is also possible to create a List<T> object using Collection Initializer as follows:
List<string> countries = new List<string>
{
      “India”,
      “Srilanka”,
      “USA”
};

How to access a Generic List<T> Collection in C#?

We can access the elements of the List<T> collection in C# using three different ways. They are as follows:

Using Index to access List<T> Collection in C#:
The List<T> Class Implements the IList<T> interface. So, we can access the individual elements of the List collection in C# by using the index. In this case, we just specify the index position of the element that we want to access. The Index is 0 Based. If the specified index is not present, then the compiler will throw an exception. The syntax is given below.
countries[0]; //First Element
countries[1]; //Second Element
countries[2]; //Thord Element

Using for-each loop to Access List<T> Collection in C#:
We can also use a for-each loop to access the elements of a List<T> collection in C# as follows.
foreach (var item in countries)
{
       Console.WriteLine(item);
}

Using for loop to Access List<T> Collection in C#:
We can also access the List<T> collection in C# using a for loop as follows. Here, we need to get the count of the list collection by using the Count properties of the List class and then start the loop from 0 and fetch the element of the list collection using the Index position.
for (int i = 0; i < countries.Count; i++)
{
        var element = countries[i];
        Console.WriteLine(element);
}

Example to Understand How to Create a List<T> Collection and Add Elements in C#:

For a better understanding of how to create a List<T> Collection and how to add elements to a list collection using Add and AddRange method, and how to access the elements of a list collection in C#, please have a look at the below example.

using System;
using System.Collections.Generic;

namespace GenericsDemo
{
    class Program
    {
        static void Main()
        {
            //Creating a Generic List of string type
            List<string> countries = new List<string>();

            //Adding Elements using Add Method
            countries.Add("INDIA");
            countries.Add("USA");

            //Creating another collection of string type
            List<string> newCountries = new List<string>();

            //Adding Elements using Add Method
            newCountries.Add("JAPAN");
            newCountries.Add("UK");

            //Adding the newCountries collection into countries collection using AddRange Method
            countries.AddRange(newCountries);

            //Accessing List Elements using ForEach Loop
            Console.WriteLine("Accessing Generic List using For Each Loop");
            foreach (var item in countries)
            {
                Console.WriteLine(item);
            }

            //Accessing List Elements using For Loop
            Console.WriteLine("\nAccessing Generic List using For Loop");
            for (int i = 0; i < countries.Count; i++)
            {
                var element = countries[i];
                Console.WriteLine(element);
            }

            //Accessing List Elements by Index Position
            Console.WriteLine("\nAccessing Individual List Element by Index Position");
            Console.WriteLine($"First Element: {countries[0]}");
            Console.WriteLine($"Second Element: {countries[1]}");
            Console.WriteLine($"Third Element: {countries[2]}");
            Console.WriteLine($"Fourth Element: {countries[3]}");

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand How to Create a List<T> Collection and Add Elements in C#

Example to Add Elements to a List using Collection Initializer in C#:

This is a new feature added to C# 3.0 which allows initializing a collection directly at the time of declaration like an array. In the below example, we are using Collection Initializer syntax instead of the Add method of the Generic List Collection class to add elements into the collection object in C#.

using System;
using System.Collections.Generic;

namespace GenericsDemo
{
    class Program
    {
        static void Main()
        {
            //Creating a Generic List of string type and adding elements using collection initializer
            List<string> countries = new List<string>
            {
                "INDIA",
                "USA",
                "JAPAN",
                "UK"
            };

            //Accessing List Elements using ForEach Loop
            Console.WriteLine("Accessing Generic List Elemenst using For Each Loop");
            foreach (var item in countries)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

Example to Add Elements to a List using Collection Initializer in C#

How to Insert Elements at a Specific Position in a C# List?

If we want to Insert Elements at a specific position in a List Collection, then we need to use the following methods provided by the Generic List Class in C#.

  1. Insert(int index, T item): This method is used to insert an element into the Generic List at the specified index. Here, the parameter index specifies the zero-based index at which an item should be inserted and the parameter item specifies the object to insert. The value can be null for reference types. If the index is less than 0 or the index is greater than Generic List Count, then it will throw ArgumentOutOfRangeException.
  2. InsertRange(int index, IEnumerable<T> collection): This method is used to insert the elements of a collection into the Generic List at the specified index. Here, the parameter index specifies the zero-based index at which an item should be inserted. The parameter collection specifies the collection whose elements should be inserted into the Generic List. The collection itself cannot be null, but it can contain elements that are null if type T is a reference type. If the collection is null, then it will throw ArgumentNullException. If the index is less than 0 or the index is greater than Generic List Count, then it will throw ArgumentOutOfRangeException.

For a better understanding of Insert and InsertRange Methods of Generic List Collection Class in C#, please have a look at the below example.

using System;
using System.Collections.Generic;

namespace GenericsDemo
{
    class Program
    {
        static void Main()
        {
            //Creating a Generic List of string type
            List<string> countries = new List<string>
            {
                "INDIA",
                "USA"
            };

            Console.WriteLine("Accessing List Elements Before Inserting");
            foreach (var item in countries)
            {
                Console.WriteLine(item);
            }

            //Insert Element at Index Position 1
            countries.Insert(1,"China");
            Console.WriteLine($"\nIndex of China Element in the List : {countries.IndexOf("China")}");

            //Accessing List After Insert Method
            Console.WriteLine("\nAccessing List After Inserting China At Index 1");
            foreach (var item in countries)
            {
                Console.WriteLine(item);
            }

            //Creating another collection of string type
            List<string> newCountries = new List<string>
            {
                "JAPAN",
                "UK"
            };

            //Inserting the newCountries collection into list at Index 2 using InsertRange Method
            countries.InsertRange(2, newCountries);

            //Accessing List After InsertRange Method
            Console.WriteLine("\nAccessing List After InsertRange At Index 2");
            foreach (var item in countries)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

How to Insert Elements at a Specific Position in a C# List?

How to Check the Availability of an Element in a List Collection in C#?

If you want to check whether an element exists or not in the List Collection, then you can use the following method of the Generic List Collection Class in C#.

  1. Contains(T item): The Contains(T item) method of the Generic List Collection Class is used to check if the given item is present in the List or not. The parameter item specifies the object to locate in the Generic List. The value can be null for reference types. It returns true if the item is found in the Generic List; otherwise, false.

Let us understand this with an example. The following example shows how to use the Contains method of the Generic List Collection class in C#.

using System;
using System.Collections.Generic;

namespace GenericsDemo
{
    class Program
    {
        static void Main()
        {
            //Creating a Generic List of string type and adding elements using collection initializer
            List<string> countries = new List<string>
            {
                "INDIA",
                "USA",
                "JAPAN",
                "UK"
            };

            //Accessing List Elements using ForEach Loop
            Console.WriteLine("All Generic List Elemenst");
            foreach (var item in countries)
            {
                Console.WriteLine(item);
            }

            //Checking the Item using the Contains method
            Console.WriteLine("\nIs INDIA Exists in List: " + countries.Contains("INDIA"));
            Console.WriteLine("Is NZ Exists in List: " + countries.Contains("NZ"));

            Console.ReadKey();
        }
    }
}
Output:

How to Check the Availability of an Element in a List Collection in C#?

How to Remove Elements from a Generic List Collection in C#?

If you want to remove elements from the list, then you can use the following methods of the List collection class.

  1. Remove(T item): This method is used to remove the first occurrence of a specific object from the Generic List. Here, the parameter item specifies the object to remove from the Generic List. It returns true if the item is successfully removed; otherwise, false. This method also returns false if the item was not found in the Generic List.
  2. RemoveAll(Predicate<T> match): This method is used to remove all the elements that match the conditions defined by the specified predicate. Here, the parameter match specifies the predicate delegate that defines the conditions of the elements to remove. It returns the number of elements removed from the Generic List. If the parameter match is null, then it will throw ArgumentNullException.
  3. RemoveAt(int index): This method is used to remove the element at the specified index of the Generic List. Here, the parameter index is the zero-based index of the element to remove. If the index is less than 0 or the index is equal to or greater than Generic List Count, then it will throw ArgumentOutOfRangeException.
  4. RemoveRange(int index, int count): This method is used to remove a range of elements from the Generic List. Here, the parameter index is the zero-based starting index of the range of elements to remove and the parameter count is the number of elements to remove. If the index is less than 0 or the count is less than 0, then it will throw ArgumentOutOfRangeException. If the index and count do not denote a valid range of elements in the Generic List, then it will throw ArgumentException.
  5. Clear(): This method is used to remove all elements from the Generic List.

For a better understanding of how to use the above methods of the Generic List Collection Class in C#, please have a look at the below example.

using System;
using System.Collections.Generic;

namespace GenericsDemo
{
    class Program
    {
        static void Main()
        {
            //Creating a Generic List of string type and adding elements using collection initializer
            List<string> countries = new List<string>
            {
                "INDIA",
                "USA",
                "JAPAN",
                "UK",
                "PAKISTAN",
                "SRILANKA",
                "BANGLADESG",
                "NEPAL",
                "CHINA",
                "NZ",
                "SOUTH AFRICA"
            };

            Console.WriteLine($"Before Removing Element Count : {countries.Count}");

            //Using Remove method to Remove an Element from the List
            Console.WriteLine($"\nRemoving Element SRILANKA : {countries.Remove("SRILANKA")}");
            Console.WriteLine($"After Removing SRILANKA Element Count : {countries.Count}");

            //Removing Element using Index Position from the List
            countries.RemoveAt(2);
            Console.WriteLine($"\nAfter Removing Index 2 Element Count : {countries.Count}");

            // Using RemoveAll method to Remove Elements from the List
            // Here, we are removing element whose length is less than 3 i.e. UK and NZ
            //countries.RemoveAll(x => x.Length < 3);
            Console.WriteLine($"\nRemoveAll Method Removes: {countries.RemoveAll(x => x.Length < 3)} Element(s)");
            Console.WriteLine($"After RemoveAll Method Element Count : {countries.Count}");

            //Removing Element using RemoveRange(int index, int count) Method
            //Here, we are removing the first two elements
            countries.RemoveRange(0, 2);
            Console.WriteLine($"\nAfter RemoveRange Method Element Count : {countries.Count}");

            //Removing All Elements using Clear method
            countries.Clear();
            Console.WriteLine($"\nAfter Clear Method Element Count : {countries.Count}");

            Console.ReadKey();
        }
    }
}
Output:

How to Remove Elements from a Generic List Collection in C#?

How to Copy an Array to a List in C#?

To Copy an Array to a List we need to use the following overloaded constructor of the List class in C#. As you

  1. public List(IEnumerable<T> collection): This constructor is used to initialize a new instance of the Generic List class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied. The parameter collection specifies the collection whose elements are copied to the new list.

For a better understanding please have a look at the below example. Here we create a List with elements from an array. We use the List constructor and pass the array as an argument. The list receives this parameter and fills its values from it. The array element type must match the List element type or compilation will fail.

using System;
using System.Collections.Generic;
namespace GenericsDemo
{
    class Program
    {
        static void Main()
        {
            // Create new array with 3 elements.
            string[] array = new string[] { "INDIA", "USA", "UK" };

            // Copy the array to a List.
            List<string> copiedList = new List<string>(array);

            Console.WriteLine("Copied Elements in List");
            foreach (var item in copiedList)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

How to Copy an Array to a List in C#?

Generic List Collection with Complex Type in C#:

Let us see an example of the List Collection class with a Complex Type in C#. As you can see in the below code, we have created a class called Employee. Then we create a few employee objects and then we create a collection of type Employee and store all the employee objects in the collection. Finally, we are performing different types of operations using the methods provided by the List<T> Generic Collection class. The following example code is self-explained. So please go through the comment lines.

using System;
using System.Collections.Generic;

namespace ListCollectionDemo
{
    public class Program
    {
        public static void Main()
        {
            // Create Employee Objects
            Employee emp1 = new Employee() { ID = 101, Name = "Pranaya", Gender = "Male", Salary = 5000 };
            Employee emp2 = new Employee() { ID = 102, Name = "Priyanka", Gender = "Female", Salary = 7000 };
            Employee emp3 = new Employee() { ID = 103, Name = "Anurag", Gender = "Male", Salary = 5500 };
            Employee emp4 = new Employee() { ID = 104, Name = "Sambit", Gender = "Male", Salary = 6500 };

            // Create a List of Employees
            List<Employee> listEmployees = new List<Employee>();

            //Adding Employees to the collection using Add Method
            listEmployees.Add(emp1);
            listEmployees.Add(emp2);
            listEmployees.Add(emp3);

            // We can retrieve the Items from a list collection by using index. 
            // The following line of code will retrieve the employee from the list. 
            // The List index is  0 based.
            Employee FirstEmployee = listEmployees[0]; //Fetch the First Add Employee from the collection

            Console.WriteLine("Retrive the First Employee By Index");
            Console.WriteLine($"ID = {FirstEmployee.ID}, Name = {FirstEmployee.Name}, Gender = {FirstEmployee.Gender}, Salary = {FirstEmployee.Salary}");
            
            //Retrieving All Employees using For loop
            Console.WriteLine("\nRetrieving All Employees using For Loop");
            for (int i = 0; i < listEmployees.Count; i++)
            {
                Employee employee = listEmployees[i];
                Console.WriteLine($"ID = {employee.ID}, Name = {employee.Name}, Gender = {employee.Gender}, Salary = {employee.Salary}");
            }

            //Retrieving All Employees using For Eacg loop
            Console.WriteLine("\nRetrieving All Employees using For Each Loop");
            foreach (Employee employee in listEmployees)
            {
                Console.WriteLine($"ID = {employee.ID}, Name = {employee.Name}, Gender = {employee.Gender}, Salary = {employee.Salary}");
            }
            
            //Inserting an Employee into the Index Position 1.
            listEmployees.Insert(1, emp4);

            //Retrieving the list after inserting the employee in index position 1
            Console.WriteLine("\nRetriving the List After Inserting New Employee in Index 1");
            foreach (Employee employee in listEmployees)
            {
                Console.WriteLine($"ID = {employee.ID}, Name = {employee.Name}, Gender = {employee.Gender}, Salary = {employee.Salary}");
            }
           
            //If you want to get the index postion of a specific employee then use Indexof() method as follows
            Console.WriteLine("\nIndex of emp3 object in the List = " + listEmployees.IndexOf(emp3));
            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string? Name { get; set; }
        public string? Gender { get; set; }
        public int Salary { get; set; }
    }
}
Output:

Generic List Collection with Complex Type in C#

Note: All the generic classes in C# are strongly typed. That means if we have created a List of type Employee, then we can only add objects of type Employee into the list. If we try to add an object of a different type, then we will get a compile-time error.

How to Find Element in a Generic List Collection in C#?

The Generic List Collection Class in C# provides a lot of useful methods that we can use to find elements on a collection of List Types. The List Collection class provides the following important methods to find elements in a collection.

  1. Find(): The Find() method is used to find the first element from a list based on a condition that is specified by a lambda expression.
  2. FindLast(): The FindLast() method is used to search for an element that matches the conditions specified by a predicate. If it found any elements with that specified condition then it returns the Last matching element from the list.
  3. FindAll(): The FindAll() method is used to retrieve all the elements from a list that matches the conditions specified by a predicate.
  4. FindIndex(): The FindIndex() method is used to return the index position of the first element that matches the conditions specified by a predicate. The point that you need to remember is the index here in generic collections is zero-based. This method returns -1 if an element that matches the specified conditions is not found. There are 2 other overloaded versions of this method is available, one of the overload versions allows us to specify the range of elements to search within the list.
  5. FindLastIndex(): The FindLastIndex() Method searches for an element in the list that matches the condition specified by the lambda expression and then returns the index of the last occurrence of the item within the list. There are 2 other overloaded versions of this method is available, one of the overload versions allows us to specify the range of elements to search within the list.
  6. Exists(): The Exists() method is used to check or determine whether an item exists or not in a list based on a condition. If the item exists then it will return true else it will return false.
  7. Contains(): The Contains() method is used to determine whether the specified item exists or not in the list. If the specified item exists then it will return true else return false.

Let us understand all the above methods of the List Collection class in C# with an Example. The following example is self-explained, so please go through the comment lines.

using System;
using System.Collections.Generic;

namespace ListCollectionDemo
{
    public class Program
    {
        public static void Main()
        {
            // Create Employee Objects
            Employee Employee1 = new Employee() { ID = 101, Name = "Pranaya", Gender = "Male", Salary = 5000 };
            Employee Employee2 = new Employee() { ID = 102, Name = "Priyanka", Gender = "Female", Salary = 7000 };
            Employee Employee3 = new Employee() { ID = 103, Name = "Anurag", Gender = "Male", Salary = 5500 };
            Employee Employee4 = new Employee() { ID = 104, Name = "Sambit", Gender = "Male", Salary = 6500 };

            //Creating a list of type Employee
            List<Employee> listEmployees = new List<Employee>
            {
                Employee1,
                Employee2,
                Employee3,
                Employee4
            };

            // use Contains method to check if an item exists or not in the list 
            Console.WriteLine("Contains Method Check Employee2 Object");
            if (listEmployees.Contains(Employee2))
            {
                Console.WriteLine("Employee2 Object Exists in the List");
            }
            else
            {
                Console.WriteLine("Employee2 Object Does Not Exists in the List");
            }

            // Use Exists method when you want to check if an item exists or not
            // in the list based on a condition
            Console.WriteLine("\nExists Method Name StartsWith P");
            if (listEmployees.Exists(x => x.Name.StartsWith("P")))
            {
                Console.WriteLine("List contains Employees whose Name Starts With P");
            }
            else
            {
                Console.WriteLine("List does not Contain Any Employee whose Name Starts With P");
            }

            // Use Find() method, if you want to return the First Matching Element by a conditions 
            Console.WriteLine("\nFind Method to Return First Matching Employee whose Gender = Male");
            Employee? emp = listEmployees.Find(employee => employee.Gender == "Male");
            Console.WriteLine($"ID = {emp?.ID}, Name = {emp?.Name}, Gender = {emp?.Gender}, Salary = {emp?.Salary}");

            // Use FindLast() method when you want to searche an item by a conditions and returns the Last matching item from the list
            Console.WriteLine("\nFindLast Method to Return Last Matching Employee whose Gender = Male");
            Employee? lastMatchEmp = listEmployees.FindLast(employee => employee.Gender == "Male");
            Console.WriteLine($"ID = {lastMatchEmp?.ID}, Name = {lastMatchEmp?.Name}, Gender = {lastMatchEmp?.Gender}, Salary = {lastMatchEmp?.Salary}");

            // Use FindAll() method when you want to return all the items that matches the conditions
            Console.WriteLine("\nFindAll Method to return All Matching Employees Where Gender = Male");
            List<Employee> filteredEmployees = listEmployees.FindAll(employee => employee.Gender == "Male");
            foreach (Employee femp in filteredEmployees)
            {
                Console.WriteLine($"ID = {femp.ID}, Name = {femp.Name}, Gender = {femp.Gender}, Salary = {femp.Salary}");
            }
            
            // Use FindIndex() method when you want to return the index of the first item by a condition
            Console.WriteLine($"\nIndex of the First Matching Employee whose Gender is Male = {listEmployees.FindIndex(employee => employee.Gender == "Male")}");
            
            // Use FindLastIndex() method when you want to return the index of the last item by a condition
            Console.WriteLine($"Index of the Last Matching Employee whose Gender is Male = {listEmployees.FindLastIndex(employee => employee.Gender == "Male")}");

            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
Output:

Generic List Collection Class in C# with Examples

Generic List Class important methods in C#:
  1. TrueForAll(): This method returns true or false depending on whether every element in the list matches the conditions defined by the specified predicate.
  2. AsReadOnly(): This method returns a read-only wrapper for the current collection. Use this method, if you don’t want the client to modify the collection i.e. add or remove any elements from the collection. The ReadOnlyCollection will not have methods to add or remove items from the collection. We can only read items from this collection.
  3. TrimExcess(): This method sets the capacity to the actual number of elements in the List if that number is less than a threshold value.
Example to Understand the above three methods of Generic List Collection Class in C#.
using System;
using System.Collections.Generic;

namespace ListCollectionDemo
{
    public class Program
    {
        public static void Main()
        {
            //Creating a list of type Employee
            List<Employee> listEmployees = new List<Employee>
            {
                new Employee() { ID = 101, Name = "Pranaya", Gender = "Male", Salary = 5000 },
                new Employee() { ID = 102, Name = "Priyanka", Gender = "Female", Salary = 7000 },
                new Employee() { ID = 103, Name = "Anurag", Gender = "Male", Salary = 5500 },
                new Employee() { ID = 104, Name = "Sambit", Gender = "Male", Salary = 6500 },
                new Employee() { ID = 105, Name = "Hina", Gender = "Female", Salary = 6500 }
            };

            //TrueForAll
            Console.WriteLine($"Are all salaries greater than 5000: {listEmployees.TrueForAll(x => x.Salary > 5000)}");
                            
            // ReadOnlyCollection will not have Add() or Remove() methods
            System.Collections.ObjectModel.ReadOnlyCollection<Employee> readOnlyEmployees = listEmployees.AsReadOnly();
            Console.WriteLine($"\nTotal Items in ReadOnlyCollection: {readOnlyEmployees.Count}");

            // listEmployees list is created with an initial capacity of 8
            // but only 5 items are in the list. The filled percentage is less than 90 percent threshold.
            Console.WriteLine($"\nList Capacity Before invoking TrimExcess: {listEmployees.Capacity}"); 

            // Invoke TrimExcess() to set the capacity to the actual number of elements in the List
            listEmployees.TrimExcess();
            Console.WriteLine($"\nList Capacity After invoking TrimExcess: {listEmployees.Capacity} "); 

            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
Output:

Generic List<T> Collection Class in C# with Examples

How to Sort a List of Simple Type in C#?

In C#, sorting a list of simple types like int, double, char, string, etc. is straightforward. Here, we just need to call the Sort() method which is provided by the Generic List class on the list instance, and then the data will be automatically sorted in ascending order. For example, if we have a list of integers as shown below.
List<int> numbersList = new List<int>{ 1, 8, 7, 5, 2};

Then we just need to invoke the Sort() method on numbersList collection as shown below
numbersList.Sort();

If you want the data to be retrieved in descending order, then use the Reverse() method on the list instance as shown below.
numbersList.Reverse();

Example to Understand Generic List Collection Class Sort and Reverse Method in C#:
using System;
using System.Collections.Generic;

namespace ListCollectionSortReverseMethodDemo
{
    public class Program
    {
        public static void Main()
        {
            List<int> numbersList = new List<int> { 1, 8, 7, 5, 2 };
            Console.WriteLine("Numbers Before Sorting");
            foreach (int i in numbersList)
            {
                Console.Write($"{i} ");
            }

            // The Sort() of List Collection class will sort the data in ascending order 
            numbersList.Sort();
            Console.WriteLine("\n\nNumbers After Sorting");
            foreach (int i in numbersList)
            {
                Console.Write($"{i} ");
            }

            // If you want to  to retrieve data in descending order then use the Reverse() method
            numbersList.Reverse();
            Console.WriteLine("\n\nNumbers in Descending order");
            foreach (int i in numbersList)
            {
                Console.Write($"{i} ");
            }

            //Another Example of Sorting String
            List<string> names = new List<string>() { "Pranaya", "Anurag", "Sambit", "Hina", "Rakesh"};
            Console.WriteLine("\n\nNames Before Sorting");
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

            names.Sort();
            Console.WriteLine("\nNames After Sorting");
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

            names.Reverse();
            Console.WriteLine("\nNames in Descending Order");
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Generic List Collection Class Sort and Reverse Method in C#

However, when we do the same thing on a complex type like Employee, Product, Customer, Department, etc. we will get a runtime exception as “invalid operation exception – Failed to compare 2 elements in the array”. This is because at runtime the .NET Framework does not identify how to sort the complex types. So, if we want to sort a complex type then we need to tell the way we want the data to be sorted in the list, and to do this we need to implement the IComparable interface. We will discuss this in our next article.

How the sort functionality is working for simple data types like int, double, string, char, etc. in C#?

This is working because these types (int, double, string, decimal, char, etc.) are already implementing the IComparable interface. If you go to the definition of any built-in types, then you will see that the class is implemented the IComparable interface.

Summary of Generic List<T> Collection Class in C#:
  1. The List<T> collection is different from the arrays. The List can be resized dynamically but arrays cannot resize dynamically.
  2. The Generic List<T> Collection Class in C# can accept null values for reference types and it also accepts duplicate values.
  3. When the element’s Count becomes equal to the Capacity of the list collection, 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.
  4. The Generic List class is the generic equivalent of the Non-Generic ArrayList class.
  5. The Generic List<T> class implements the IList<T> generic interface.
  6. We can use both equality and ordering comparer with the generic List class.
  7. The List<T> class elements are not sorted by default and elements are accessed by a zero-based index.
  8. For very large List<T> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

In the next article, I am going to discuss How to Sort a List of Complex Types in C# with Examples. Here, in this article, I try to explain the Generic List<T> Collection Class in C# with Examples. I hope this Generic List Collection Class in C# with Examples article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Generic List Collection in C#”

  1. blank

    Guys,
    Please give your valuable feedback. And also, give your suggestions about the Generic List Collection Class concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to Generic List, you can also share the same.

Leave a Reply

Your email address will not be published.