Showing posts with label Lambda. Show all posts
Showing posts with label Lambda. Show all posts

Friday, August 22, 2008

Linq - A Basic Understanding

LINQ (Language Integrated Query) is provides a universal way to query your data and objects.
You use LINQ to query objects, SQL and XML.

Linq relies heavily on delegates, anonymous methods and lambda expressions.

The foundation layout is as follows:
  • Delegates exist for situations in which you want to pass methods around to other methods.
  • An anonymous method is a block of code that is used as the paremeter for the delegate.
  • Lambda expresions can be used with delegate types.

Using lambda expression reduces the number classes.

Lamba expressions can be used any place where type is a delegate.

The method that is invoked by the delegate does not need the exact same types ad defined by the delegate declaration. Convariance and contra-variance are possible.

  • Return Type Convariance is when the return type can derive from the type defined in the delegate.
  • The term parameter type contra-variance means that the parameters defined by the delegate might differ in the method that is called by the delegate.

To the left of the Lambda operator => are the parameters. It is ok not to added the parameter types because they are resolved by the compiler. The right side of the Lambda operator defines the implementation. With anonymous methods, curly brackets and the return statement are required. With Lambda expressions the syntax elements are not required because they are done by the compiler in any case. If you have move than one statement on the right side of the Lambda operator, curly brackets and the return stement are possible.

LINQ example

var query = from r in BroncRider.GetChampions() where r.State == "SD" orderby r.Wins decending select r;

for each (BroncRider in query) {Console.Writeline("{0:A}", r);

Notes:

  • where r.State == "SD" is converted to Where (r => r.State == "SD")
  • .orderby r.Wins decending is converted to OrderByDecending(r => r.wins)

The query expression must begin with a from clause and end with a select or group clause.

When the query expression is defined during runtime, the query does not run. The query runs when the items are iterated.

Let's have a look once more at the extension method Where(). This extension method makes use of the yield return statement to return the elements where the predicate is true. Because the yield return statement is used, the compiler creates an enumerator and returns the items as soon as they are access from the enumeration.

The collection is also to be sorted. This does not happen when the query is defined. Instead the iteration happens with the foreach statement, where all the items are iterated. Basically, the sort happens whenever you do a foreach. If you add items to the collection and later iteratate the items they will be sorted.