Convert an Integer Array to a List in C#

C# | Converting an integer array to a list: Here, we are going to learn how to convert a given an integer array to a list in C#? By IncludeHelp Last updated : April 15, 2023

What is a List?

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.

Converting int[] to List<int>

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

How to convert an integer array to a list?

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.

Syntax

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

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

The following code shows to convert an integer array to a list:

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

Here, arr is the input array.

The following syntax shows to declare an integer array:

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

C# program to convert an integer array a list

using System;
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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.