Search This Blog

2009-04-18

USING LAMBARD EXPRESSION

USING LAMBARD EXPRESSION,INTRO DUCTION TO LAMBARD EXPRESSION

Lambda Expressions are based on functional calculus—Lambda Calculus—from the 1930s, and Lambda Expressions exist in other languages.Think of Lambda Expressions as brief inline functions whose concise nature is an ideal fit for LINQ.


Lambda Expressions are written with a left side, the => symbol, and a right side, as in(x,y) => x + y;.
The left side represents the input arguments and the right side is theexpression to be evaluated.

For example(x,y) => x + y;is read x and y goes to—or as I read it gosinta—the function x + y.

Implicit in the expression is the return result of x + y.

The input argument or arguments can be inferred and generated by the compiler, called implicit arguments, or expressed explicitly by you.
The preceding Lambda Expression can also be rewritten as(int x, int y) => x + y;

class Program{

static void Main(string[] args) {

Func<int, int, int> add = (int x, int y) => x + y; Console.WriteLine(add(3, 4)); Console.ReadLine(); }}[/code]
You can begin exploring how Lamba Expressions support LINQ queries by seeing howLambda Expressions are used in extension methods such as Select, Where, orOrderBy.
Using Select<T> with Lambda Expressions
Check the following example:[code] var numbers = new int[]{1,2,3,4,5,6}; foreach(var result in numbers.Select(n => n)) Console.WriteLine(result);[/code]
Here we are executing the SELECT * behavior of SQL queries by initializing the Select extension method with n => n. n => n means that n is the input and you want to return n.
Using Where<T> with Lambda Expressions
The Where extension method is employed in scenarios where you would use conditional logic to filter the elements returned in a resultset. Like Select, Where returns an IEnumerable, where T is defined by the type of the result from the Lambda Expression.
[code] var words = new string[]{"Drop", "Dead", "Fred"}; IEnumerable<string> hasDAndE = words.Where(s => s.Contains('D') && s.Contains('e')); foreach(string s in hasDAndE) Console.WriteLine(s);[/code]
Using OrderBy<T> with Lambda Expressions
OrderBy is the extension method that supports sorting. OrderBy accepts a Func genericdelegate. The Func argument can be expressed with a literal Lambda Expression.
[code]
var numbers = new int[] {1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };IEnumerable<int> ordered = numbers.OrderBy(n=>n); foreach(var num in ordered) Console.WriteLine(num);[/code]

No comments: