Using Let Keyword in Linq

I am using Linq-To-Object in my current project to remove some extra loops and I have found one of the great keyword in Linq called ‘Let’. Let keyword provides facility to declare a temporary variable inside the Linq Query.We can assign the result of manipulation to temporary variable inside query and we can use that temporary variable to another manipulation.

Let’s take a simple example of Linq query I am using an integer array to find square and after finding the square of the integer value I will use let keyword to find square value which are greater then 20. Here is the my query for that.

protected void Page_Load(object sender, EventArgs e)
{

int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
var Result = from i in intArray
let square = i * i
where square>20
select square;
foreach (int i in Result)
{
Response.Write(i.ToString());
Response.Write("\n");
}
}

 

Here is the result of that query as expected.


LetResult

 Let keyword is more useful when you are working with directories and files,xml manipulations so here possibilities are unlimited. Hope this will help you.. Happy Programming!!!


Technorati Tags: ,,
Shout it
Published Wednesday, August 25, 2010 1:18 AM by Jalpesh P. Vadgama
Filed under: , ,

Comments

# re: Using Let Keyword in Linq

Wednesday, August 25, 2010 3:11 AM by safknw

Very useful tip.

Thanks

# re: Using Let Keyword in Linq

Wednesday, August 25, 2010 10:06 AM by Julien

nice I never see this keyword and I'm a fan of LINQ! I will use it!

# re: Using Let Keyword in Linq

Wednesday, August 25, 2010 11:51 AM by Jalpesh P. Vadgama

@safknw and @Julien

Thanks for nice comments!!

# re: Using Let Keyword in Linq

Wednesday, August 25, 2010 10:57 PM by TaoYang

Nice example, thanks!

# re: Using Let Keyword in Linq

Thursday, August 26, 2010 7:37 PM by hajan

very good example!

# Let Result | More More Pics

Saturday, March 12, 2011 4:10 PM by Let Result | More More Pics

Pingback from  Let Result | More More Pics

# Object Oriented Programing » Using Let Keyword in Linq

Wednesday, April 13, 2011 10:25 AM by Object Oriented Programing » Using Let Keyword in Linq

Pingback from  Object Oriented Programing » Using Let Keyword in Linq