Mohanapriya R Mohanapriya R
Updated date Sep 02, 2024
In this article, we will learn how to convert IEnumerable collections to arrays in C#.
  • 1.8k
  • 0
  • 0

Converting IEnumerable to Array: 

Converting IEnumerable to an array involves a few steps. First, we will initialize an IEnumerable collection with some elements. Then, we will use LINQ's ToArray() method or the toArray() extension method to convert the IEnumerable to an array. 

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

class Program
{
    static void Main(string[] args)
    {
        // Initializing an IEnumerable collection
        IEnumerable<int> numbers = Enumerable.Range(1, 5);

        // Converting IEnumerable to array using LINQ
        int[] array1 = numbers.ToArray();

        // Converting IEnumerable to array using toArray() extension method
        int[] array2 = numbers.ToArray<int>();

        // Outputting the arrays
        Console.WriteLine("Array 1:");
        foreach (var num in array1)
        {
            Console.WriteLine(num);
        }

        Console.WriteLine("\nArray 2:");
        foreach (var num in array2)
        {
            Console.WriteLine(num);
        }
    }
}

Output:

Upon running the above program, you should see the following output:

Array 1:
1
2
3
4
5

Array 2:
1
2
3
4
5

Comments (0)

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