What is the purpose of "ToArray" operator in LINQ?
The purpose of the ToArray
operator in LINQ is to convert a sequence (collection) into an array. It allows you to materialize the query results or convert the sequence into an array, which is a commonly used data structure in C#.
Here's the syntax of the ToArray
operator in LINQ:
T[] array = sequence.ToArray();
-
sequence
represents the collection or sequence of elements that you want to convert into an array.
Example:
using System;
using System.Linq;
class Program
{
static void Main()
{
// Define a class for Person
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// Create an array of Person objects
Person[] people = new Person[]
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 17 },
new Person { Name = "Charlie", Age = 30 },
new Person { Name = "David", Age = 16 }
};
// Use LINQ to query and filter people who are over 18 years old
var query = from person in people
where person.Age > 18
select person;
// Convert the query results to an array
Person[] adultsArray = query.ToArray();
// Display the names of adults
Console.WriteLine("Adults in the array:");
foreach (var adult in adultsArray)
{
Console.WriteLine($"Name: {adult.Name}, Age: {adult.Age}");
}
}
}
Output:
Adults in the array:
Name: Alice, Age: 25
Name: Charlie, Age: 30
In this program, we define a Person
class with properties for Name
and Age
. We create an array of Person
objects called people and use LINQ to query and filter individuals who are over 18
years old. The query results are then converted to an array using the ToArray
operator. Finally, we display the names and ages of the adults in the array.
The ToArray
operator is useful when you need to work with the query results as an array. Arrays provide efficient storage and quick access to elements. By using ToArray
, you can easily convert a LINQ query result or sequence into an array for further processing or use in your code.