Defining a variable inside a Linq query (let C# with Example



Defining a variable inside a Linq query (let C# with Example

keyword) 
In order to define a variable inside a linq expression, you can use the let keyword. This is usually done in order to 
store the results of intermediate sub-queries, for example: 
int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
var aboveAverages = from number in numbers 
let average = numbers.Average() 
let nSquared = Math.Pow(number,2) 
where nSquared > average 
select number; 
Console.WriteLine("The average of the numbers is {0}.", numbers.Average()); 
foreach (int n in aboveAverages) 
 

{ 
Console.WriteLine("Query result includes number {0} with square of {1}.", n, Math.Pow(n,2)); 
} 
Output: 
The average of the numbers is 4.5. 
Query result includes number 3 with square of 9. 
Query result includes number 4 with square of 16. 
Query result includes number 5 with square of 25. 
Query result includes number 6 with square of 36. 
Query result includes number 7 with square of 49. 
Query result includes number 8 with square of 64. 
Query result includes number 9 with square of 81. 
View Demo 

0 Comment's

Comment Form

Submit Comment