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
Tweet
1 comment:
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.
Post a Comment