Using from-let-where Clause in LINQ

In this example, we will see how to use the from-let-where clause in LINQ. For this purpose, let us take a sample array and then print only those numbers in this array, whose square is greater than 10.

static void Main(string[] args)
{
// code from DevCurry.com
var arr = new[] { 5, 3, 4, 2, 6, 7 };
var sq = from int num in arr
let square = num * num
where square > 10
select new { num, square };

foreach (var a in sq)
Console.WriteLine(a);

Console.ReadLine();
}

As shown above, the from clause specifies the source data collection. The let clause takes the evaluation of the square and assigns it to a variable which can be used in the where clause. The where clauses eliminates each set of numbers from the array whose square is not greater than 10. Finally the select clause creates an object of an anonymous type which is printed on the console.

Shown below is the ouput of only those numbers whose square is greater than 10

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Anonymous said...

Interesting option to be aware of.

I've always done such parameters in the Select, as such:
var x = from i in ints
select { Number = i,
Square = i * i }

I can see Let being a lot more readable though.