Language

Enumerable.ToList(IEnumerable) Method

Definition

Creates a List from an IEnumerable.

public:
generic 
[System::Runtime::CompilerServices::Extension]
 static System::Collections::Generic::List ^ ToList(System::Collections::Generic::IEnumerable ^ source);
public static System.Collections.Generic.List ToList(this System.Collections.Generic.IEnumerable source);
static member ToList : seq<'Source> -> System.Collections.Generic.List<'Source>

Public Function ToList(Of TSource) (source As IEnumerable(Of TSource)) As List(Of TSource)

Type Parameters

TSource

The type of the elements of source.

Parameters

source
IEnumerable

The IEnumerable to create a List from.

Returns

A List that contains elements from the input sequence.

Exceptions

source is null.

Examples

The following code example demonstrates how to use ToList to force immediate query evaluation and return a List that contains the query results.

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

List 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
*/
' Create an array of strings.
Dim fruits() As String =
{"apple", "passionfruit", "banana", "mango",
 "orange", "blueberry", "grape", "strawberry"}

' Project the length of each string and
' put the length values into a List object.
Dim lengths As List(Of Integer) =
fruits _
.Select(Function(fruit) fruit.Length) _
.ToList()

' Display the results.
Dim output As New System.Text.StringBuilder
For Each length As Integer In lengths
    output.AppendLine(length)
Next
Console.WriteLine(output.ToString())

' This code produces the following output:
'
' 5
' 12
' 6
' 5
' 6
' 9
' 5
' 10

Remarks

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

ToArray has similar behavior but returns an array instead of a List.

Applies to