C# List Class |Top 12 Amazing Generic List Methods

C# List
List in C# – Methods and Properties

In C#, the List<T> class is a generic type used to represent the collection of strongly typed objects that can be accessed via index or loops. The List<T> class is available in the System.Collection.Generic namespace.
It allows you to search, sort, manipulate, add, and remove elements from the collection of strongly typed objects.
In C#, Arrays, Queues, Linked lists, and other single-dimensional data structures have been replaced by the generic list. Because it has so many additional characteristics, such as the ability to dynamically expand in size when an item is added.

The above diagram illustrates the methods and properties of the List class.

C# List<T> (List) Characteristics

    • The List<T> class is a generic type that allows you to store only items of the same data type.
    • The List<T> class is available in the System.Collections.Generic namespace.
    • List<T> is type-safe, T stands for type, used to describe the type of object you want to store in the list.
    • The compiler will check if you only add the correct object type to the list, otherwise a compile time error will occur.
    • To retrieve elements of the generic list collection, you can use loops or an index. e.g. myGenericList[0].
    • A generic list in C# can be dynamically expand while arrays cannot.
    • 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> class is equivalent to the ArrayList class. It implements the generic IList<T> interface.

Declaration of a List in C#

The following is the syntax for declaring a generic List< T >. 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>();

How to create a generic List<T> in C#?

The following is an example of using generic lists in C#.

List<T> example

In the example below, we’ll create a generic list of strings that uses the Add() method to store items and iterates the list using the foreach loop.

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.
To add various new items to an existing list with a single sentence, use the following syntax:

Example1-Add() and AddRange() method of the generic List<T> class.

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");

Example2-Adding items to the C# List<T> class

// 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);

Example3-Insert elements into C# List using Insert() or InsertRange() methods.

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 if you run the above C# program.

Print List elements
Print List elements

C# List<T> – Check Elements in List

Use the Contains() method to test for the presence of an item 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 using List<T>.IndexOf method

The following is an example of searching string 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

How to Access List Elements?

In C#, List is a generic collection. We can use either for or foreach loop to iterate the List elements.
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("** 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.
Count– This property indicates the number of elements contained in the List.
Capacity– This property indicates a list’s capacity or the number of elements it can hold.

C# List<T>.Count Property

The following example demonstrates how to count the numbers 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

C# List<T>.Capacity Property

The Capacity property is used to get or set the maximum amount of elements that the internal data structure 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.

C# List<T>.Remove(T) Method

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 also 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

C# List<T>.RemoveAt(Int32) Method

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

When you use 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

C# List<T>.RemoveAll(Predicate) Method

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 List 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

C# List<T>.RemoveRange(Int32, Int32) Method

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

C# List<T>.Clear Method

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

C# List<T>.Sort Method

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

The following code example shows how to sort the items in the 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

C# List<T>.Reverse Method

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#

In C#, List is a class that represents a list of items that can be individually accessed by index, whereas IList is an interface that represents a collection of objects that can be accessed by index.
The IList interface implements two interfaces: ICollection and IEnumerable.

C# List 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 class represents a list of elements that can be accessed individually by the index (or loops).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 ‘numberList’ object above simply 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 in C#, its methods, and its properties. In this article, we learned how to add, insert, delete, find, search, sort, and reverse items in the generic List.

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. C# Struct vs Class
    3. Exception Handling in C#| Use of try, catch and finally block
    4. C# Enum 
    5. C# extension methods with examples
    6. Properties In C# with examples
    7. IEnumerable Interface in C# with examples
    8. Constructors in C# with Examples
    9. C# Dictionary

Leave a Reply