Mohanapriya R Mohanapriya R
Updated date Aug 28, 2024
In this blog, we will learn how to convert arrays to lists using C#.
  • 5.9k
  • 0
  • 0

Array to List Conversion in C#:

To convert an array to a list in C#, we can use the ToList() method provided by the System.Linq namespace. This method is an extension method for arrays, allowing for a smooth transition between the two data structures.

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

class Program
{
    static void Main()
    {
        // Create an array
        int[] integerArray = { 1, 2, 3, 4, 5 };

        // Convert the array to a list
        List<int> integerList = integerArray.ToList();

        // Display the original array
        Console.WriteLine("Original Array:");
        foreach (var item in integerArray)
        {
            Console.Write(item + " ");
        }

        // Display the converted list
        Console.WriteLine("\n\nConverted List:");
        foreach (var item in integerList)
        {
            Console.Write(item + " ");
        }
    }
}

Output:

Original Array:
1 2 3 4 5

Converted List:
1 2 3 4 5

In this program, we create an array named integerArray and then use the ToList() method to convert it into a list (integerList). Finally, we display both the original array and the converted list to observe the successful conversion.

The ToList() method is part of the LINQ (Language-Integrated Query) library, and it provides an easy way to convert various types of collections, including arrays, into lists. This conversion allows developers to leverage the additional functionalities and methods offered by lists, such as dynamic resizing, insertion, and deletion of elements.

Comments (0)

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