This blog is moved to

Thursday, May 21, 2009

Linq and C# - Part 1

Linq => Language Integrated Query

3 Parts of Linq Query

1. Obtain data source
2. Create the query
3. Execute the query

static void Main()
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.
// numQuery is an IEnumerable
var numQuery =
from num in numbers
where (num % 2) == 0
select num;

// 3. Query execution.
foreach (int num in numQuery)
Console.Write("{0,1} ", num);


In LINQ the execution of the query is distinct from the query itself;in other words you have not retrieved any data just by creating a query variable.

The datasource must support IEnumerable interface.


The query expression contains three clauses: from, where and select. The from clause specifies the data source, the where clause applies the filter, and the select clause specifies the type of the returned elements.


the query variable itself only stores the query commands. The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. This concept is referred to as deferred execution.

Forcing Immediate Execution : Queries that perform aggregation functions over a range of source elements must first iterate over those elements. Examples of such queries are Count, Max, Average, and First. These execute without an explicit foreach statement because the query itself must use foreach in order to return a result.

No comments: