C# Enumerable ToList

Description

Creates a List from an IEnumerable.

Syntax


public static List<TSource> ToList<TSource>(
  this IEnumerable<TSource> source
)

Parameters

  • TSource - The type of the elements of source.
  • source - The IEnumerable to create a List from.

Example

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


// w  w  w.  ja  v  a 2 s .c  om
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  

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

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

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

  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable