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
Copy the entire LinkedList to Array in C#
The LinkedList<T> class in C# provides the CopyTo() method to copy all elements from a LinkedList to an array. This method is useful when you need to convert a dynamic LinkedList structure into a fixed-size array for processing or storage.
Syntax
Following is the syntax for copying a LinkedList to an array −
linkedList.CopyTo(array, arrayIndex);
Parameters
-
array − The one-dimensional array that is the destination of elements copied from LinkedList.
-
arrayIndex − The zero-based index in array at which copying begins.
Using CopyTo() Starting from Index 0
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
LinkedList<int> list = new LinkedList<int>();
list.AddLast(100);
list.AddLast(200);
list.AddLast(300);
int[] strArr = new int[5];
list.CopyTo(strArr, 0);
foreach(int str in strArr){
Console.WriteLine(str);
}
}
}
The output of the above code is −
100 200 300 0 0
Using CopyTo() Starting from a Specific Index
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
LinkedList<int> list = new LinkedList<int>();
list.AddLast(100);
list.AddLast(200);
list.AddLast(300);
int[] strArr = new int[10];
list.CopyTo(strArr, 4);
foreach(int str in strArr){
Console.WriteLine(str);
}
}
}
The output of the above code is −
0 0 0 0 100 200 300 0 0 0
Using CopyTo() with String LinkedList
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
LinkedList<string> list = new LinkedList<string>();
list.AddLast("Apple");
list.AddLast("Orange");
list.AddLast("Banana");
string[] fruits = new string[5];
list.CopyTo(fruits, 1);
Console.WriteLine("Array contents:");
for(int i = 0; i < fruits.Length; i++){
Console.WriteLine($"Index {i}: {fruits[i] ?? "null"}");
}
}
}
The output of the above code is −
Array contents: Index 0: null Index 1: Apple Index 2: Orange Index 3: Banana Index 4: null
Conclusion
The CopyTo() method provides an efficient way to copy all elements from a LinkedList to an array. You can specify the starting index in the destination array, making it flexible for inserting LinkedList elements at any position within the target array.
