How to Use LINQ ToArray in C# - Simple Guide
ToArray() in LINQ to convert an IEnumerable sequence into an array. It creates a new array containing all elements from the sequence in the same order.Syntax
The ToArray() method is called on an IEnumerable<T> sequence to create a new array of type T[]. It does not take any parameters.
Syntax:
var array = sourceSequence.ToArray();Here, sourceSequence is any collection or query result that implements IEnumerable<T>.
var array = sourceSequence.ToArray();Example
This example shows how to use ToArray() to convert a list of numbers into an array and print each element.
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 10, 20, 30, 40 }; int[] array = numbers.ToArray(); foreach (int num in array) { Console.WriteLine(num); } } }
Common Pitfalls
1. Forgetting to include using System.Linq;: The ToArray() method is an extension method in the System.Linq namespace, so you must include this using directive.
2. Calling ToArray() on null: If the source sequence is null, calling ToArray() will throw a ArgumentNullException. Always ensure the source is not null.
3. Expecting ToArray() to modify the original collection: It creates a new array copy and does not change the original collection.
/* Wrong: Missing using System.Linq; */ // List<int> numbers = new List<int> {1, 2, 3}; // int[] arr = numbers.ToArray(); // Error: ToArray() not found /* Correct: */ using System.Linq; List<int> numbers = new List<int> {1, 2, 3}; int[] arr = numbers.ToArray();
Quick Reference
- Purpose: Convert
IEnumerable<T>toT[]array. - Namespace:
System.Linq - Returns: New array with elements in original order.
- Throws:
ArgumentNullExceptionif source is null.