Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to convert an array to an ordinary list with the same items
Converting an array to a list is a common operation in C#. There are several ways to achieve this conversion, from manual iteration to using built-in methods that make the process more efficient and concise.
Using Manual Loop
The most straightforward approach is to create an empty list and add each array element using a loop −
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
int[] arr = { 23, 66, 96, 110 };
var list = new List<int>();
for (int i = 0; i < arr.Length; i++) {
list.Add(arr[i]);
}
foreach(int res in list) {
Console.WriteLine(res);
}
}
}
The output of the above code is −
23 66 96 110
Using List Constructor
The List<T> constructor can accept an IEnumerable<T>, making array-to-list conversion much simpler −
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
string[] fruits = { "Apple", "Banana", "Cherry", "Date" };
var list = new List<string>(fruits);
Console.WriteLine("List created from array:");
foreach(string fruit in list) {
Console.WriteLine(fruit);
}
Console.WriteLine("List count: " + list.Count);
}
}
The output of the above code is −
List created from array: Apple Banana Cherry Date List count: 4
Using ToList() Extension Method
The LINQ ToList() extension method provides the most concise way to convert arrays to lists −
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public static void Main() {
double[] numbers = { 1.5, 2.7, 3.14, 4.8, 5.2 };
var list = numbers.ToList();
Console.WriteLine("Original array length: " + numbers.Length);
Console.WriteLine("List count: " + list.Count);
Console.WriteLine("\nList contents:");
foreach(double num in list) {
Console.WriteLine(num);
}
}
}
The output of the above code is −
Original array length: 5 List count: 5 List contents: 1.5 2.7 3.14 4.8 5.2
Comparison of Methods
| Method | Syntax | Requires LINQ | Performance |
|---|---|---|---|
| Manual Loop | for loop + Add() |
No | Good control, more verbose |
| List Constructor | new List<T>(array) |
No | Efficient, clean syntax |
| ToList() Method | array.ToList() |
Yes | Most concise, requires using System.Linq |
Conclusion
Converting arrays to lists in C# can be accomplished through manual loops, the List constructor, or the LINQ ToList() method. The List constructor approach offers the best balance of simplicity and performance, while ToList() provides the most concise syntax when LINQ is already included in your project.
