ToArray Method
public static T[] ToArray<TSource>(this IEnumerable<TSource> source)
Description
Converts an IEnumerable<TSource>
to an array.
This extension method is part of the LINQ to Objects implementation and provides a convenient way to materialize the results of a query into a T array.
Returns
An array of type TSource
that contains the elements of the specified sequence.
Remarks
If the input sequence is empty, an empty array is returned.
This method is useful for eager evaluation of a query, for example, to cache results or to pass to methods that require an array.
The returned array is a snapshot of the sequence at the time the method was called. Subsequent modifications to the source sequence will not affect the array.
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
// Create a list of integers
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Use ToArray to convert the list to an array
int[] numberArray = numbers.ToArray();
Console.WriteLine("Array elements:");
foreach (int number in numberArray)
{
Console.WriteLine(number);
}
// Example with a query
var evenNumbersQuery = from num in numbers
where num % 2 == 0
select num;
int[] evenNumberArray = evenNumbersQuery.ToArray();
Console.WriteLine("\nArray of even numbers from query:");
foreach (int number in evenNumberArray)
{
Console.WriteLine(number);
}
}
}