178-linq-let-clause-let-keyword-using-c

Reading Time: 1 minute

LINQ Let clause i.e. LINQ Let Keyword is a part of a query expression. Let clause allows LINQ query expression to be more readable and code to be shorter and easier to understand. Let also introduces variable that can be used later in the query. In here, there are two examples. In the first example, we create a set of absolute values from initial array by using let clause.

double[] set3 = { -1.0, 2.0, -3.0, 4.0, -5.0, 6.0 };
var query1 = from n in set3

let s = Math.Abs(n)

select s;

double[] absolut = query1.ToArray();
string str_absolut = String.Join(“,”, absolut);
MessageBox.Show(str_absolut,”Abs values”);

If we want to make array of absolute integer values by using let clause and ternary operator ? : we can do it following way:

int[] set3 = { 1, -11, 2 , -45, 40 };

var query1 = from n in set3

let s = (n > 0 ? n : -1*n )

select s;

In the third example, we calculate standard deviation (variance) by using let keyword in LINQ expression to find squared values of difference between every particular array member and average value.

double[] numbers = { 5.0, 0.0, 4.0, 1.0, 3.0, 6.0, 2.0 };
double average = numbers.Average();

var query1 = from n in numbers

let s = (n – average) * (n – average)

select s;

double[] squared = query1.ToArray();
double variance = squared.Sum() / ((double)squared.Length – 1.0);
variance = Math.Sqrt(variance);

In all examples, we use let clause to introduce new variable in our query, and later this variable is selected.

External links:

LINQ Let Clause LINQ Let Keyword on Dotnetperls
LINQ Let Clause LINQ Let Keyword on Codeproject
LINQ Let Clause LINQ Let Keyword on C-sharpcorner
LINQ Let Clause LINQ Let Keyword on Stackoverflow
LINQ Let Clause LINQ Let Keyword on Microsoft

Leave a Reply

Your email address will not be published. Required fields are marked *

*