C# ToList

List type.

ToList converts collections to List instances. It provides a fast and easy-to-remember method that returns a List instance with the appropriate elements. It simply creates a new List for you internally. This method is found in the System.Linq namespace.

This C# tutorial shows how to use the ToList extension method from System.Linq.

Example

Note

This program instantiates an array with an array initializer and then converts that object data into a List instance. The System.Linq namespace is included in the compilation unit and this allows us to invoke the ToList() extension method on the array reference. The List data is then printed to the screen.

Program that uses ToList extension method [C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	//
	// Use this input string[] array.
	// ... Convert it to a List with the ToList extension.
	//
	string[] array = new string[]
	{
	    "A",
	    "B",
	    "C",
	    "D"
	};
	List<string> list = array.ToList();
	//
	// Display the list.
	//
	Console.WriteLine(list.Count);
	foreach (string value in list)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

4
A
B
C
D
Conversion or change

Overview. This program introduces the Main entry point, and in the method body an array is allocated. It uses an array initializer to specify that the array has four elements. Next, the ToList() extension method is called on that array reference. ToList() is an extension method from the System.Linq namespace, but is called in the same way as an instance method is called. The ToList method returns a new List of string type instances and this List is displayed to the screen.

Array Initializer Examples

Internals

.NET Framework information

The ToList method internally checks its parameter for null, which will occur if you try to use ToList on a null reference. The ToList extension method then invokes the List type constructor with the instance parameter. This means that using "instance.ToList()" is equivalent to using "new List<T>(instance)" where T is the type.

Key point: ToList extension method just calls the List constructor.

Summary

The C# programming language

We examined the ToList extension method in the C# programming language, noting its usage in a trivial program and also its implementation in the .NET base class library. Internally, the ToList extension method invokes the List type constructor, meaning its performance characteristics are about the same. It provides a more declarative syntax for creating a List instance through a method call.

Extension Method LINQ Examples
.NET