C# program to create a List with elements from an array


Set an array −

int[] val = new int[5];

// integer elements
val[0] = 15;
val[1] = 25;
val[2] = 40;
val[3] = 58;
val[4] = 70;

Now set a list and add array in it −

List<int> myList = new List<int>(val);

The following is the code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      int[] val = new int[5];
      // integer elements
      val[0] = 15;
      val[1] = 25;
      val[2] = 40;
      val[3] = 58;
      val[4] = 70;
      List<int> myList = new List<int>(val);
      Console.WriteLine("Elements...");
      foreach(int res in myList) {
         Console.WriteLine(res);
      }
      // count integer elements
      Console.WriteLine("Number of elements: "+myList.Count);
   }
}

Output

Elements...
15
25
40
58
70
Number of elements: 5

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements