.NET API Documentation

Enumerable.ToList Method

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

Description

Converts an IEnumerable<T> to a List<T>. This is a convenience method that allows you to easily create a list from any sequence of elements.

Parameters

Name Type Description
source IEnumerable<TSource> An IEnumerable<T> to convert to a List<T>.

Returns

Type Description
List<TSource> A List<T> that contains the elements from the input sequence.

Generic Type Parameters

TSource: The type of the elements in the source sequence.

Examples

C# 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 numbers = new List { 1, 2, 3, 4, 5 };

        // Use ToList() to create a new list from an existing list
        List anotherList = numbers.ToList();

        Console.WriteLine("Original List:");
        foreach (int num in numbers)
        {
            Console.Write($"{num} ");
        }
        Console.WriteLine();

        Console.WriteLine("New List created using ToList():");
        foreach (int num in anotherList)
        {
            Console.Write($"{num} ");
        }
        Console.WriteLine();

        // Using ToList() with a LINQ query
        var evenNumbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        List evenNumbersList = evenNumbers.Where(n => n % 2 == 0).ToList();

        Console.WriteLine("Even numbers list:");
        foreach (int num in evenNumbersList)
        {
            Console.Write($"{num} ");
        }
        Console.WriteLine();
    }
}
                    

See Also