Mohanapriya R Mohanapriya R
Updated date Feb 15, 2024
In this article, we will learn how to convert IEnumerable collections to List efficiently in C#.

Introduction:

When working with collections in C#, you often encounter scenarios where you need to convert an IEnumerable to a List. While both IEnumerable and List are interfaces for representing collections of objects, they differ in functionality and usage. In this article, we will explore how to perform this conversion efficiently and effectively.

Before exploring the conversion process, let's understand the key differences between IEnumerable and List. IEnumerable is the most basic interface for iterating over a collection, providing a generic way to traverse through elements. On the other hand, List is a concrete implementation of ICollection and IList interfaces, offering additional features such as random access and dynamic resizing.

Program:

To convert an IEnumerable to a List, you can leverage the List constructor that accepts an IEnumerable parameter. Here's a simple example demonstrating this conversion:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        IEnumerable<int> numbers = Enumerable.Range(1, 5);
        List<int> numberList = new List<int>(numbers);

        Console.WriteLine("Converted List:");
        foreach (var num in numberList)
        {
            Console.WriteLine(num);
        }
    }
}

Output:

Converted List:
1
2
3
4
5

In this example, we start with an IEnumerable<int> collection generated using Enumerable.Range method. Then, we initialize a new List<int> by passing the IEnumerable collection as an argument to the List constructor. Finally, we iterate through the elements of the resulting List and display them.

It's important to note that the conversion process involves iterating over the entire IEnumerable collection to populate the List. This operation can have performance implications, especially for large collections. Additionally, the resulting List is mutable, allowing for efficient random access and modification of elements.

When to use List over IEnumerable? Lists are ideal for scenarios where you require frequent access to elements by index or need to modify the collection frequently. They offer better performance for operations like adding, removing, or accessing elements at specific positions.

Conclusion:

In summary, converting IEnumerable to List in C# is a straightforward process that involves using the List constructor. By understanding the differences between IEnumerable and List and considering the specific requirements of your application.

Comments (0)

There are no comments. Be the first to comment!!!