Mohanapriya R Mohanapriya R
Updated date Jun 06, 2024
In this article, we will learn how to convert IEnumerable collections to List efficiently in C#.
  • 1.6k
  • 0
  • 0

Introduction:

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.

To convert an IEnumerable to a List, you can use the List constructor that accepts an IEnumerable parameter. 

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

class Program
{
    static void Main()
    {
        IEnumerable<int> numbers = Enumerable.Range(1, 7);
        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
6
7

This program we will use an IEnumerable<int> collection to generate the numbers using Enumerable.Range method. Then, we will initialize a new List<int> by passing the IEnumerable collection as an argument to the List constructor. Finally, we will use the foreach to print the output from the numberlist.

Comments (0)

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