forcing immediate execution of linq query

Usually Linq queries are stored in a variable and executed when the variable is iterated using a for loop. This method of execution is useful when we want to retrieve data from a data source multiple times during the program execution. For instance, suppose we want to retrieve data and display it after update then this method of execution is useful.

However, there will be many instances when we want to cache results after querying. In such situations immediate execution is the preferred method. One such instance is when we want to store the query result in a collection object like List or Array.

The ToList method is used to store the query result in a List after execution. Similarly the ToDictionary method stores the query result in a Dictionary after execution and the ToArray method stores the query result in a array.

The following code uses the ToList method to immediately execute a query and stores the result of a query into a list.

DBDataContext ctx = new DBDataContext();
 var proQuery =  from p in ctx.Products
    			 select c;
 List pList = proQuery.ToList();


Queries that perform aggregate operations first iterate over elements in a data source and return a single result. Examples of aggregate operators are Count, Max and Average. When we use these operators, queries execute immediately without using an explicit for each loop. The following example counts the number of categories in a list.

List categories = new List(); 
categories.Add("Vegetables");     
categories.Add("Fruits");                   
categories.Add("Non Sodium Items");                                
categories.Add("Bakery Products");
var catQuery = (from cat in categories
			select cat).Count();
Console.WriteLine(catQuery);
Console.ReadLine();