Convert an integer array to the list in C#

C# changing over an integer array to the rundown: Here, we will figure out how to change over a given an integer array to the rundown in C#?

Given an integer array and we need to change over it into a rundown in C#.

Changing over int[] to List<int>

A rundown is utilized to speak to the rundown of the articles, it is spoken to as List, where T is the sort of the rundown objects/components.

A rundown is a class which goes under System.Collections.Generic bundle, so we need to incorporate it first.

To change over an integer array to the rundown, we use toList() technique for System.Linq. Here, is the syntax of the articulation that changes over an integer array to the rundown.

    List<T> arr_list = array_name.OfType<T>().ToList();

Here, T is the sort and array_name is the info array.

Example (for integer array)

    List<int> arr_list = arr.OfType<int>().ToList();

Here, arr is the information array.

Syntax:

    var array_name = new[] {initialize_list/elements};

C# program to change over an integer array to the rundown:

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


namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr = new[] { 10, 20, 30, 40, 50 };

            //creating list 
            List<int> arr_list = arr.OfType<int>().ToList();

            //printing the types of variables
            Console.WriteLine("type of arr: " + arr.GetType());
            Console.WriteLine("type of arr_list: " + arr_list.GetType());

            Console.WriteLine("List elements...");
            //printing list elements 
            foreach (int item in arr_list)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();


            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output:

type of arr: System.Int32[]
type of arr_list: System.Collections.Generic.List`1[System.Int32]
List elements...
10 20 30 40 50

Leave a Comment

error: Alert: Content is protected!!