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<T> 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<Customer> 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.



cover image of azure cloud book

Create an Azure Cloud Software Application

View Highlights » View Contents »
cover image of foundation database programming book

Create your Own Accounting Software

View Highlights » View Contents »
cover image of ERP book

Create your Own ERP Software

View Highlights » View Contents »
cover image of asp.net book

Create your Own WEB ERP Software using ASP.Net

View Highlights » View Contents »
cover image of entity framework book

Create your Own Entity Framework Application (SOM System)

View Contents »
cover image of Android book

Create your Own Android Database Application (SOM System)

View Contents »