C# List Class: Top 10+ Generic List Methods

C# List class represents a strongly typed list of objects that can be accessed via index. It allows you to search, sort, add, remove, and manipulate list elements. It is available in System.Collections.Generic namespace.

The following diagram illustrates the methods and properties of the List<T> class.

C# List
List in C#

A List class can be used to create a collection of any data type. For example, we can create a list of Integer, double, long, string, or even any complex type.

The generic List<T> is a replacement for an array, linked list, stack, queue, and other one-dimensional data structures. This is because it has all kinds of extra functionality, such as the ability to dynamically resize when items are added or removed from the list.

Declaration of a List<T> in C#

The following is the syntax to declare a generic List<T> in C#. The parameter T in the list represents the type of item in the list, which can be int, long, string, or any user-defined object.

List<T> genericList = new List<T>();

List<T> Characteristics

  • A List<T> is a generic collection that can only contain elements of a specific type. It provides compile-time type checking and avoids boxing-unboxing.
  • It is available in the System.Collections.Generic namespace.
  • You can use a loop or an index to retrieve elements from the generic list. For example myGenericList[0].
  • We can add elements to the list by using the Add(), and AddRange() methods or collection-initializer syntax.
  • A generic list can be dynamically resized but arrays can’t.
  • The generic List<T> class permits null as a valid value for the reference type.
  • The C# List<T> class can also store duplicate items.
  • The generic List<T> is equivalent to the ArrayList, which implements IList<T> interface.

Creating a List<T>

The following is an example to create a generic list in C#.

Here, we will create a generic list of strings that stores items using the Add() method and iterates the list using the foreach loop.

List<T> example:

using System;
using System.Collections.Generic;
namespace ListInCSharp
{
    public class Program
    {
        public static void Main()
        {
            // Creating and Initializing a generic list with items

            List<string> listOfNames = new List<string>()
            {"Shekh Ali", "Victoria"};

            // Adding new items
            listOfNames.Add("Alexander");
            listOfNames.Add("Sofia");
            listOfNames.Add("Ayesha");

            // Iterates the list items using the foreach loop.
            Console.WriteLine("** C# List - Print names using foreach loop ** \n");
            foreach (string name in listOfNames)
            {
                Console.WriteLine($" {name} ");
            }
            Console.ReadKey();
        }
    }
}
CSharp List Class example
Output – CSharp List Class example

How to add items to a C# List?

You can add items to a generic List by using the Add() or AddRange() methods.

Example 1:

The addRange() method allows adding elements of the specified collection to the end of the generic list.

// AddRange method
 listOfNames.AddRange(new string[]
        {
        "Raj",
        "Simran"
        });

 // Add method
 listOfNames.Add("Romeo");

Example 2:

// Collection of string  
string[] names = {"Muhammad", "Mahatma Gandhi", "Abraham Lincoln", "Nelson Mandela" };  

// Creating a string-type generic List and adding a collection to it.
List<string> listOfNames = new List<string>();  
                           // AddRange method
                           listOfNames.AddRange(names);

Example 3:

The following is an example of inserting items into the list using the Insert and InsertRange methods.

using System;
using System.Collections.Generic;
namespace ListInCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating and initializing a list
            List<String> fruitsNameList = new List<String>() { "Apple", "Avocado" };

            // inserting elements into list using List method
            fruitsNameList.Insert(0, "Banana");
            fruitsNameList.Insert(3, "Grapes");

            List<String> fruitsName = new List<String>() { "Mango", "Orange" };

            // Inserting fruitsName into fruitsNameList at position 1
            // InsertRange method
            fruitsNameList.InsertRange(1, fruitsName);
            Console.WriteLine("****** Print list elements ******");
            foreach (string item in fruitsNameList)
            {
                Console.WriteLine($" {item} ");
            }

            Console.ReadLine();
        }
    }
}

You will get the following result once you run the above C# program.

Print List elements
Print List elements

C# List<T> – Check Elements in List

The Contains() method can be used to determine if an item is present in the list.

The following code snippet contains the List.Contains() method to check if an item exists in the list or not. If the item is available in the List, it returns true, otherwise, it returns false.

            // Creating and initializing a list of numbers
            List<int> listOfNumbers = new List<int>() { 10, 20, 30, 40, 50, 60, 70, 80 };
            listOfNumbers.Contains(20); // returns true
            listOfNumbers.Contains(25); // returns false
            listOfNumbers.Contains(40); // returns true  

Find an element in the List<T>

The following is an example of searching for a string item and its position in the list.
If the item is found, the IndexOf method returns 0; otherwise -1.

using System;
using System.Collections.Generic;
namespace ListInCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating and initializing a list
            // IndexOf method
            List<string> listOfCountries = new List<string>() { "India", "Australia","France" };
            int num1 = listOfCountries.IndexOf("India"); // return 0 ; means item found
            int num2 = listOfCountries.IndexOf("China"); // return -1 ; means item not found


            string str1 =  num1 >= 0 ?  $"Country '{listOfCountries[num1]}' found at {num1} index" 
            :"Not found";
            string str2 =  num2 >= 0 ?  $"Country '{listOfCountries[num2]}' found at {num2} index" 
             :"Not found";

            Console.WriteLine($" {str1} \n {str2}");
            Console.Read();

        }
    }
}
// Output:
// Country 'India' found at 0 index
// Not found

Accessing a List

List elements can be accessed by an index, a for/foreach loop, or using LINQ queries as well. Indexes of a list start from zero.

In the following code snippet, we are using for and foreach loops to access list items.

using System;
using System.Collections.Generic;
namespace ListInCSharp
{
    public class Program
    {
        public static void Main()
        {
            List<int> numbers = new List<int>()
            { 10, 20, 30, 40, 50 };

            // Console.WriteLine(numbers[0]); // prints 10
            Console.WriteLine("** C# List - Print using for loop ** \n");
            // Accessing list elements using for loop

            for (int index = 0; index < numbers.Count; index++)
                Console.WriteLine($" {numbers[index]} ");

            Console.WriteLine("** C# List - Print using foreach loop ** \n");
            // Accessing list elements using for loop

            foreach(int number in numbers)
                Console.WriteLine($" {number} ");

            Console.ReadKey();
        }
    }
}

C#-Generic List<T> properties

There are primarily two properties in the list.

List PropertyDescription
Count:The count property returns the total number of elements that exist in the List<T>
Capacity:It indicates the capacity or the number of elements a list can store.

Count items in the List<T>

The following example demonstrates how to count the number of items in a List.

 List<int> numbers = new List<int>() { 10, 20, 30, 40, 50 };
        // Print the number of elements in the List.
            Console.WriteLine(numbers.Count); // Prints - 5

Capacity Property of List<T>

The Capacity property is used to get or set the maximum amount of elements that the list can hold without having to resize it.

            List<int> list = new List<int>();
            Console.WriteLine(list.Capacity); // Prints 0

            // List<int> list = new List<int>(5);
            // OR
            list.Capacity = 5;
            list.Add(10);
            list.Add(20);
            Console.WriteLine(list.Capacity); // Prints 5

Removing elements from the list in C#

We can utilize list methods like Remove, RemoveAt, RemoveAll, RemoveRange, and Clear to remove items from a generic list.

Remove Method of C# List<T>

The Remove method deletes the first occurrence of the specified item in the List.
If the item is successfully removed, this method returns true; otherwise, false. If the item is not found in the generic List, this method will return false.

This method is used to remove the first instance of the duplicate item from the list.
The code below removes the first occurrence of the number “10” from the given list.

 public static void Main()
        {
            List<int> list = new List<int>()
            { 10, 10, 20, 30, 40, 50 };

            // Remove method
            list.Remove(10);
            foreach (int item in list)
            Console.Write($" {item} ,"); 
            Console.ReadKey();
        }
        //Output:
        //10 , 20 , 30 , 40 , 50

RemoveAt Method Of C# List<T>

In C#, the RemoveAt() method removes the element at the specified index of the List.

When you use the RemoveAt() method to remove an item from the list, the remaining items are renumbered to replace the one that was removed. When the item at index 2 is removed, the item at index 3 is moved to the 2 positions.

 public static void Main()
        {
            List<int> list = new List<int>()
            {10, 20, 30, 40, 50 };

            // RemoveAt method to remove item from a given position
            list.RemoveAt(2);
            foreach (int item in list)
            Console.Write($" {item} ,"); 
            Console.ReadKey();
        }
        //Output:
        //10 , 20 , 40 , 50

RemoveAll Method of C# List<T>

The RemoveAll() method is used to remove all elements from the list that match the predicate conditions. The elements of the current List are sent to the Predicate<T> delegate individually, and the elements that match the conditions are deleted.

The following example demonstrates the RemoveAll() method of the List class that uses the Predicate generic delegate.

public static void Main()
        {
            List<int> list = new List<int>() {10, 20, 30, 40, 50 };

            // RemoveAll() method to remove numbers less than 40 from a list.
            list.RemoveAll(items => items < 40);
            Console.WriteLine(string.Join(", ", list));      
            Console.ReadKey();
        }
        //Output:
        //40, 50

RemoveRange Method of C# List<T>

The RemoveRange method removes a list of elements from the given index to the specified count. We must pass the starting index and count as method parameters.
The following example demonstrates the RemoveRange method.

public static void Main()
        {
            List<int> list = new List<int>()
            {10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

            // RemoveRange() method, to remove items from 0 to 2 index from a list.

            list.RemoveRange(0, 2);
            Console.WriteLine(string.Join(", ", list));
            
            Console.ReadKey();
        }
        //Output:
        // 30, 40, 50, 60, 70, 80, 90, 100

Clear Method of C# List<T>

To remove all elements from a generic List, use the Clear() method.

In the following example, the Clear method is used to delete all elements from a list

public static void Main()
        {
            List<int> list = new List<int>()
            {10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

            Console.WriteLine($" Count before calling the Clear() method : {list.Count} ");

            // Clear() method to delete all the elements from the list.
            list.Clear();

            Console.WriteLine($" Count after calling the Clear() method : {list.Count} ");

            Console.ReadKey();
        }
        //Output:
        // Count before calling the Clear() method : 10
        // Count after calling the Clear() method : 0

Sort Method of C# List<T>

This method is used to sort the elements in the entire List using the default comparer.

Example:

The following code example shows how to sort the items in the generic List.

public static void Main()
        {
            List<int> list = new List<int>()
            {10, 30, 20, 50, 40, 60, 70, 90, 80, 100 };

            Console.WriteLine("** Befor Sorting **");
            Console.WriteLine(string.Join(" , ",list));

            // Sort() method
            list.Sort();

            Console.WriteLine("** After Sorting **");
            Console.WriteLine(string.Join(" , ", list));           

            Console.ReadKey();
        }
        //Output:
         //** Befor Sorting **
        // 10 , 30 , 20 , 50 , 40 , 60 , 70 , 90 , 80 , 100
        // ** After Sorting **
        // 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 , 100

Reverse Method of C# List<T>

The Reverse() method is used to reverse the order of the elements in the entire List.
This method uses  Array.Reverse  method to internally reverse the order of the elements in the generic list.

The following code example shows how to reverse the items in the List.

 public static void Main()
        {
            List<char> list = new List<char>()
            {'A', 'B', 'C', 'D'};

            // Reverse() method
            list.Reverse();

            Console.WriteLine(string.Join(" , ", list));           

            Console.ReadKey();
        }
        //Output:
        // D , C , B , A

Difference between List and IList in C#

C# List<T> ClassIList Interface
The List is a concrete class in C#An IList is an interface that the List class implements.
In C#, the List class can be instantiated.You Cannot instantiate the IList interface; instead, you must create an object of the type that implements the IList interface.
The List<T> class represents a list of elements that can be accessed individually by the index (or loops).The IList is an interface that represents a collection of objects that can be accessed through an index.
Difference between List and IList interface in C#
IList<int> numberList = new List<int>();

The above-mentioned numberList object has the IList interface’s methods only.

List<int> numberList = new List<int>();

The numberList object above simply has all members of the List Class.

Reference MSDN: List<T> Class

Conclusion

This article demonstrates the basics of the generic List<T> in C#, including its methods, and properties. Here, we also learned how to add, insert, delete, find, search, sort, and reverse items in the generic List.

Recommended Articles:

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments