structure of a linq query


Let us discuss the structure and how a language integrated query looks like. We will write the query code and then discuss the structure. A LINQ query looks as shown below.

var queryByCountry =
      from cust in customers
      where cust.Age < 20 
      group cust by cust.Country
      select cust;
foreach (string c in queryByCountry)
{          
	Console.WriteLine(c.Name);       
}
The above query retrieves all the customers in the �customers� collection, filters them with the condition �Age< 20� and groups them by their country.

The first clause in the query is the �from� clause. This clause is used to identify the data source and the variable called range variable that is used to iterate through the elements of the data source. The data source can be a list or dictionary or a database table. In the above query customers is the collection and cust is the range variable. The range variable can be best understood by considering the for loop. A for loop has a variable referred to as iteration variable.

The where clause sets the condition for filtering the data from the data source. The condition in this query is - age of customers is less than 20 years. The select clause is used to select the fields for each item to be retrieved. These clauses - from, where, group, select are called standard query operators. The entire query given above is stored in the query variable �queryByCountry�.