Mohanapriya R Mohanapriya R
Updated date Aug 08, 2024
In this article, we will learn about the differences between List and IEnumerable in C# and how to convert List to IEnumerable with a simple example program.

How to Convert List to IEnumerable in C#

This C# program converts a List to an IEnumerable:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Create a List of integers
        List<int> numbersList = new List<int> { 1, 2, 3, 4, 5 };

        // Convert the List to an IEnumerable
        IEnumerable<int> numbersEnumerable = numbersList;

        // Iterate over the IEnumerable and print each element
        foreach (int num in numbersEnumerable)
        {
            Console.WriteLine(num);
        }
    }
}

In the above program, we have created a list of integers that contain some values. Then, we used a simple assignment statement to convert the List to an IEnumerable, storing the result in a variable called numbersEnumerable. At the end, we iterated over the IEnumerable using a foreach loop and print each element to the console as shown below.

Output:

1
2
3
4
5

Comments (0)

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