In LINQ, the ToList operator takes the elements from the given source and returns a new List. So that means the input would be converted to type List.
Syntax of LINQ ToList() Operator
Following is the syntax of using LINQ ToList() to convert input collection to list.
LINQ ToList() Syntax in C#
List<string> result = countries.ToList();
LINQ ToList() Syntax in VB.NET
Dim result As List(Of String) = countries.ToList()
If you observe above syntax we are converting “countries” collection to list using LINQ ToList() operator.
LINQ ToList() Operator in Method Syntax Example
Following is the example of using LINQ ToList() to convert input collection to a List in method syntax.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
{
class Program
{
static void Main(string[] args)
{
string[] countries = { "US", "UK","India", "Russia", "China", "Australia", "Argentina" };
List<string> result = countries.ToList();
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
VB.NET Code
Module Module1
Sub Main()
Dim countries As String() = {"US", "UK", "India", "Russia", "China", "Australia", "Argentina"}
Dim result As List(Of String) = countries.ToList()
For Each s As String In result
Console.WriteLine(s)
Next
Console.ReadLine()
End Sub
End Module
If you observe the above example we are converting countries collection to List by using LINQ ToList () method.
Output of LINQ ToList() Operator Example
Following is the result of the LINQ ToList() operator in the method syntax example.
US
UK
India
Russia
China
Australia
Argentina
LINQ ToList() in Query Syntax Example
Following is the example of using the LINQ ToList() operator in query syntax.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExamples
{
class Program
{
static void Main(string[] args)
{
string[] countries = { "US", "UK","India", "Russia", "China", "Australia", "Argentina" };
List<string> result = (from x in countries select x).ToList();
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
VB.NET
Module Module1
Sub Main()
Dim countries As String() = {"US", "UK", "India", "Russia", "China", "Australia", "Argentina"}
Dim result As List(Of String) = (From x In countries).ToList()
For Each s As String In result
Console.WriteLine(s)
Next
Console.ReadLine()
End Sub
End Module
Result of LINQ ToList() in Query Syntax
Following is the result of using the LINQ ToList() operator in query syntax.
US
UK
India
Russia
China
Australia
Argentina
This is how we can use LINQ ToList() operator/method to convert given collection items to the new list.