LINQ Architecture


Language-Integrated Query (LINQ) is a new feature introduced in visual studio 2008 and .NET Framework 3.5. Developers can write the queries in the code to retrieve the data from various types of data sources like SQL,XML and XQuery.

Earlier developers has to learn the syntax for writing queries for each data source. LINQ simplifies by offering a model to work with the data across various kinds of data sources.

LINQ Architecture


By using LINQ you can query and transform the data in

  • XML Document
  • SQL Databases
  • ADO.NET Datasets
  • .NET Collections

LINQ Query operation contains three parts

1. Obtain the data source.

2. Create the Query.

3. Execute the Query.

LINQ Example

class LINQExample
    static void Main()
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        string[] names = new string[4] { “TOM”, “DAN”, “ADAMS”, “BERNARD” };

        // 2. Query creation.
        // nameQuery is an IEnumerable<string>
        var nameQuery =
            from name in names 
            where name == “TOM”
            select name;

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

Important thing to notice is when write a query it do not retrieve any data. In order to get the data from data source  you need to execute the query.

The data source in the above example is Array and implicitly supports IEnumerable interface. All types that support IEnumerable<T> are called queryable types.

Query expression contains three clauses from, where and select.

The from clause specifies the data source, where clause applies the filter and select clause specifies the types of returned elements.

Query executes in foreach statement in the example. The actual execution of the query starts when iterate over the query variable in foreach statement.

Forcing Immediate Execution

Queries that perform aggregate operations must first iterate over those elements. Example Count, Max and Average.

These execute without an explicit foreach statement.

int nameCount = nameQuery .Count();

%d bloggers like this: