Home » C#.Net

Convert an integer array to the list in C#

C# | converting an integer array to the list: Here, we are going to learn how to convert a given an integer array to the list in C#?
Submitted by IncludeHelp, on March 11, 2019

Given an integer array and we have to convert it into a list in C#.

Converting int[] to List<int>

A list is used to represent the list of the objects, it is represented as List<T>, where T is the type of the list objects/elements.

A list is a class which comes under System.Collections.Generic package, so we have to include it first.

To convert an integer array to the list, we use toList() method of System.Linq. Here, is the syntax of the expression that converts an integer array to the list.

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

Here, T is the type and array_name is the input array.

Example (for integer array)

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

Here, arr is the input array.

Syntax:

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

C# program to convert an integer array to the list

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.