convert a sequence to a generic list using ToList()method
LINQ queries have a unique feature. They are run only when we attempt to consume the result. For example, when a forloop is used, the query is run only when we iterate through the result. This is referred to as deferred evaluation. Given below is a LINQ to SQL query which runs against a database.
However, there are some methods which force immediate evaluation of a LINQ query. ToList() is one such method. When used, LINQ evaluates the query immediately. The ToList() method converts a LINQ var into a List
object. Then we can bind the list to any data bound controls like DataGrid or Listbox control etc.
Example1:
SalesDBDataContext dataContext = new SalesDBDataContext();
var custQuery =
from c in dataContext.Customers
select c;
List qList = custQuery.ToList();
Example2:
SalesDBDataContext dataContext = new SalesDBDataContext();
var custQuery =
from c in dataContext.Customers
select new {c.CustomerId, c.Name };
var qList = custQuery.ToList();
The above query returns anonymous type and ToList() method converts anonymous type into a list.