C# Create List from Array - Tutorial Kart

[Pages:4]C# Create List from Array

C# ? Create List from Array

In C#, array is a collection of elements that belong to basic/strong datatypes. List can contain elements belonging to more generic datatype, unlike an array.

In this tutorial, we shall learn how to create a C# List from an Array.

To create a List from Array, pass the array to the List constructor while creating a new List. Also, please note that the datatype of elements in the list should match the datatype of elements in the array.

Example 1 ? Create C# List from Array

In this example, we have an array of integers numbers . We shall create a list nums using array numbers . As the array contains elements of type integer, you can create a list of integers only.

Program.cs

using System; using System.Collections.Generic; class Program {

static void Main(string[] args) { //array int[] numbers = {10, 20, 30, 40}; //create list from array List nums = new List(numbers); //print list foreach (int num in nums) { Console.WriteLine(num); }

} }

Run the above C# program. Now the new list contains all the elements of the array.

Output

10 20 30

30 40

Example 2 ? Create C# List from String Array

In this example, we shall create List of Strings from an Array of Strings. As already mentioned, datatypes of elements in array and list has to match.

Program.cs

using System; using System.Collections.Generic; class Program {

static void Main(string[] args) { //array string[] numbers = {"One", "Two", "Three"}; //create list from array List nums = new List(numbers); //print list foreach (string num in nums) { Console.WriteLine(num); }

} }

Run the above C# program.

Output

One Two Three

Conclusion

In this C# Tutorial, we learned how to create a list from a given array.

C# Tutorial C# Tutorial C# Basic Example C# Comments C# Variables

C# Variables C# Constants C# if, if-else C# switch C# while loop C# for loop C# foreach C# break C# continue C# struct C# enum C# String C# Array C# Command Line Arguments

C# Console Operations C# Write to Console C# Read from Console

C# Object Oriented Programming Concepts C# Class & Constructors C# Encapsulation C# Polymorphism C# Method Overloading C# Interfaces

C# String Operations C# String Length C# Substring

C# File Operations C# Read Text File C# Write to File C# Delete File

C# Delete File C# Copy File

C# Exception Handling C# try-catch C# finally C# throw C# Custom Exception C# SystemException C# DivideByZeroException C# NullReferenceException C# InvalidCastException C# IOException C# FieldAccessException

C# Collections C# List C# SortedList C# HashSet C# SortedSet C# Stack C# Queue C# LinkedList C# Dicionary C# SortedDictionary

C# Errors [Solved] C# Error: Class does not contain a constructor that takes arguments

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download