Thursday, December 29, 2011

LINQ Review


A little review for those that never really embraced the beginnings of LINQ:

LINQ is an acronym for Language Integrated Query which allows you to write structured type-safe queries over object collections. It was new as of .NET 3.0 in C#. The basic LINQ query can be run over any collection implementing IEnumerable<> and are compile-type checked. The core namespaces supporting LINQ are System.Linq and System.Linq.Expressions in the Systems.Core assembly.
The basic units of LINQ are sequences and elements. A sequence is any object that implements the generic IEnumerable interface and an element is each item in the sequence.
string[] michael = { "Jon", "Mikal", "Brad" };
In this example Michael is the sequence and Jon, Brad and Mikal are the elements.
A query operator is a method that transforms a sequence. In the Enumerable class in System.Linq there are around 40 query operators, all implemented as static extension methods, called standard query operators. A query is an expression that transforms sequences with query operators. The most basic queries have one input sequences and one operator. In the following example, the Where operator is applied on a simple array to extract those names that have at least 4 letters:
string[] michael = { "Jon", "Mikal", "Brad" };
       IEnumerable<string> filtered = Enumerable.Where( michael, m => m.Length >= 4 );

       foreach ( var item in filtered )
       {
              Console.WriteLine( item + "|" );  // Mikal|Brad|
       }

This query could further be shortened by implicitly typing michael:
var filtered = michael.Where( m => m.Length >= 4 );
Most query operators take a lambda expression as an argument. This expression helps shape the query, the lambda expression from above is:
m => m.Length >= 4
                The input argument, in this case m corresponds to an input element. In the above example the input argument represents the names in the array and is of type string. This operator, Where, requires that the lambda expression return a boolean value which if true in this case means the element should be included in the output sequence. These types of queries are commonly referred to as lambda queries. There is also in C# a special syntax for writing these queries called query comprehension syntax. The above lambda query can be re-written in query comprehension syntax as follows:
       IEnumerable<string> filtered = from m in michael
                                     where m.Length >= 4
                                     select m;

                Both types of queries work together to provide a much easier way of iterating elements in a sequence.               

No comments: