0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ ToArray in C# - Simple Guide

Use 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>.

csharp
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.

csharp
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);
        }
    }
}
Output
10 20 30 40
⚠️

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.

csharp
/* 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> to T[] array.
  • Namespace: System.Linq
  • Returns: New array with elements in original order.
  • Throws: ArgumentNullException if source is null.

Key Takeaways

Always include 'using System.Linq;' to access ToArray().
ToArray() creates a new array from any IEnumerable sequence.
Do not call ToArray() on a null collection to avoid exceptions.
The original collection remains unchanged after ToArray().
Use ToArray() when you need a fixed-size array from a query or collection.