LINQ ToList Query Operator

By Peter Bromberg

The ToList<TSource>(IEnumerable<TSource>) method forces immediate query evaluation and returns a List<T> that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.

string[] fruits = { "apple", "passionfruit", "banana", "mango",
"orange", "blueberry", "grape", "strawberry" };

List<int> lengths = fruits.Select(fruit => fruit.Length).ToList();

foreach (int length in lengths)
{
Console.WriteLine(length);
}

/*
This code produces the following output:

5
12
6
5
6
9
5
10
*/

LINQ ToList Query Operator  (1227 Views)