C# List Class: Learn All You Need to Know About List in C#

Are you a C# developer looking to master lists in C#? This tutorial will guide you through everything you need to know about using lists in C#, including how to create, add items, loop through, sort, reverse, remove, and clear items from a list.

We will also cover using list properties, inserting items at specific positions, finding and importing items from other lists, converting a list to an array, and joining two lists.

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

C# List
List in C#

01. What is C# List?

A List is a dynamic data structure in C# that allows you to store and manipulate a collection of objects. It represents a strongly typed list of objects that we can access via index. It will enable you to search, sort, add, remove, and manipulate list elements.

 A List in C# is similar to an array but more flexible, as it can be resized dynamically, allowing for adding and removing elements without manually resizing the list. 

A List in C# is part of the System.Collections.Generic namespace.

We can use a List class to create a collection of any data type. For example, we can create a list of Integer, double, long, string, or any complex type.

Syntax

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

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

02. How to create a List in C#?

To create a List in C#, you first need to create an instance of the List class. You can create a List using the generic List<T> class, where T is the type of the elements you want to store in the List. Here is an example of how to create a List of integers:

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

In this example, we created a new List of integers named myIntList. The new keyword is used to create a new instance of the List class, and the angle brackets <> are used to specify the type of elements in the list, which in this case is int.

03. How do you add an item to a C# List?

To add an item to a List in C#, you can use the Add method, which is available on all List objects. Here is an example of how to add an integer value to a List:

myIntList.Add(1);
myIntList.Add(2);
myIntList.Add(3);

In this example, we added the integer value 1,2 and 3 to our myIntList List. You can add any type of object to a List in C#, as long as it matches the type specified when the List was created.

04. How do you loop through a C# List?

To loop through a List in C#, you can use a foreach loop, which iterates over each element in the List. Here is an example of how to loop through our myIntList List and print each element to the console:

foreach (int index in myIntList)
{
    Console.Write(index);
}
// Output: 1 2 3

In this example, we used a foreach loop to iterate over each element in the myIntList List, and we used the variable index to hold the current element of the List. We then printed the value of the index to the console.

05. How do you use C# List properties?

A List in C# has several properties that we can use to manipulate and query the List. Some of the most commonly used properties of a List in C# are:

  • Count: It returns the number of elements in the List.
  • Capacity: It returns the current capacity of the List.
  • IsReadOnly: It returns a Boolean value indicating whether the List is read-only.

Here is an example of how to use the Count property to get the number of elements in our myIntList List:

int count = myIntList.Count; // Output: 4

In this example, we used the Count property of our myIntList List to get the number of elements in the List and store them in the count variable.`

06. How to insert an item at a position in a C# List?

You can use the Insert method to insert an item at a specific position in a List in C#. Here is an example of how to insert an integer value of 4 at the 4th position in the myIntList List:

myIntList.Insert(3, 4);

In this example, we used the Insert method to insert the integer value of 4 at the 4th position (index 3) in the myIntList List. The first argument to the Insert method is the index at which to insert the element, and the second argument is the element to insert.

07. How do you remove an item from a C# List?

You can use the Remove method to remove an item from a List in C#. Here is an example of how to remove the first occurrence of an integer value of 3 from the myIntList List:

myIntList.Remove(3);

In this example, we used the Remove method to remove the first occurrence of the integer value of 3 from the myIntList List. No action is taken if the element is not found in the List.

08.How do you check if an item exists in a C# List?

You can use the Contains method to check if an item exists in a List in C#. Here is an example of how to check if the integer value of 2 exists in our myIntList List:

bool exists = myIntList.Contains(2); // Returns: True

In this example, we used the Contains method to check if the integer value of 2 exists in the myIntList List. The Contains method returns a Boolean value indicating whether the element is found in the List.

09. How do you sort a C# List?

You can use the Sort method to sort a List in C#. Here is an example of how to sort our myIntList List in ascending order:

myIntList.Sort();

In this example, we used the Sort method to sort the myIntList List in ascending order. The Sort method is available on all List objects and can be used to sort a List of any type that implements the IComparable interface.

10. How do you reverse a C# List?

You can use the Reverse method to reverse the order of a List in C#. Here is an example of how to reverse the order of our myIntList List:

myIntList.Reverse(); //Output: 4 3 2 1

In this example, we used the Reverse method to reverse the order of the elements in the myIntList List.

11. How do you find an Item in a C# List?

You can use the Find method to find an item in a List in C#. Here is an example of how to find the first occurrence of an integer value that is greater than 3 in our myIntList List:

int greaterThanThree = myIntList.Find(x => x > 3);

In this example, we used the Find method to find the first occurrence of an integer value greater than 3 in the myIntList List. The Find method takes a delegate function that defines the conditions of the element to search for and returns the first element that matches the condition.

12. How to import items to a C# List from another List?

To import items from another List in C#, you can use the AddRange method. Here is an example of how to add all elements from a sourceList to a destinationList:

        List<int> sourceList = new List<int>();
        sourceList.Add(1);
        sourceList.Add(2);
        sourceList.Add(3);

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

        destinationList.AddRange(sourceList);
        foreach (int i in destinationList)
        Console.Write($"{i}"); //Output: 3 2 1

In this example, we used the AddRange method to add all elements from the sourceList to the destinationList. We can use the AddRange method to add multiple elements to a List at once.

13. How do you convert a C# List to an array?

To convert a List to an array in C#, you can use the ToArray method. Here’s an example of how to convert the myIntList List to an integer array:

int[] myIntArray = myIntList.ToArray();

In this example, we used the ToArray method to convert the myIntList List to an integer array.

14. How do you join two C# Lists?

You can use the Concat method to join two Lists in C#. Here is an example of how to concatenate two integer Lists in C#:

        List<int> list1 = new List<int>() { 1, 2, 3 };
        List<int> list2 = new List<int>() { 4, 5, 6 };
        List<int> concatenatedList = list1.Concat(list2).ToList();
        foreach (int item in destinationList)
        Console.Write(item); //Output: 1 2 3

In this example, we used the Concat method to concatenate two integer Lists, list1 and list2. The Concat method returns a new List that contains all the elements from both Lists.

15. How do you clear all items from a C# List?

You can use the Clear method to remove all items from a List in C#. Here is an example of how to clear all items from our myIntList List:

 myIntList.Clear();// Clear list
int count = myIntList.Count;
Console.WriteLine(count); // Output:0

In this example, we used the Clear method to remove all elements from the myIntList List.

16. Capacity Property of List in C#

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

Characteristics of the List class in C#

Here are some of the key characteristics of the List class in C#:

  1. A List is a collection of objects that can grow or shrink dynamically as items are added or removed.
  2. A List is an ordered collection, meaning that the items in the List have a specific order and can be accessed by index.
  3. A List can store any object, including value types like int and double, reference types like string and custom classes, and other collections like List <T> or Dictionary<K, V>.
  4. We can initialize a List with an initial capacity, which can improve performance when adding many items to the List.
  5. A List supports many useful methods, such as adding and removing items, searching for items, sorting the List, and more.
  6. A List can be easily converted to an array using the ToArray method, which can be helpful in passing the List’s contents to other methods or APIs that expect an array.
  7. A List can be enumerated using a foreach loop, which simplifies the process of iterating over the items in the List.

Overall, the List class in C# is handy for managing collections of objects that need to be dynamically resized or manipulated in various ways. Its versatility and rich set of methods make it a powerful tool for various programming tasks.

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

Example:

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

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.

a. 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

b. RemoveAt() Method Of C# List

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

c. RemoveAll() Method of C# List<T>

The RemoveAll() method removes 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

d. RemoveRange() Method of C# List

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

e. 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

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:

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments