Archives par mot-clé : it

use of lambda statement in C # 3

use of lambda statement in C #

by Mohamed Ali Ettougourti


Our study of  lambda expression use n in c sharp continues.

Driven by curiosity that programming needs justify we can ask if the vector object of our attention has a single value that continues throughout the vector as length and as big as it is.

The lambda expression  is a good relief because we can use the query « All » to see if all the values of a vector are identical.

The statement « all » returns a Boolean value « yes » or « no », true or false.

So back to our vector k int initiated in the previous articles we can examine to see if all vector values are zero.

int [] k = {2, 1, 2, 3, 5, 3, 4, 1, 6, 7, 8, 2, 1, 0, 8};

bool vrai= k.All (b => b == 0);

the function returns false  what is true because some values of the vector k are different from 0.

One can ask on a different way to see if all values are greater than 0.

 vrai  = k.All (b => b> 0);

the answer is always negative since we know a glance to the vector k is a value at least equal  to zero.

Exasperated we want to finish by asking directly and frankly the question: is there any value in the vector that is zero?

This is the Any instruction that comes to our rescue, our curiosity will be satisfied

v = k.Any (b => b == 0);

Once the variable “v” is true and the answer is positive.

Some propose to assure the existence of a zero value in our vector k we taking differently but always using the valuable services of our lambda expression.

It is true that c sharp offer another instruction that seems a priori meet the same spots.

The « first » instruction, since it is from which it comes, would check for a value in a vector.

int [] k = {2, 1, 2, 3, 5, 3, 4, 1, 6, 7, 8, 2, 1, 0, 8};

int  occ =  k.First (b => b == 3);

if it is true that the first instruction using the lambda expression confirms our intuition of the existence of a value equal to 3 belonging to the vector,  the instruction, however, merely refers quite simply the desired value.

By inspecting the variable « occ » we « discovered » no surprise it  is equal to 3. What we know already. Thanks anyway.

The instruction « first » seems unnecessary especially when checking we discover that the instruction really has a very bad temper. You be the judge.

If you ever ask the help of the first instruction to search for a value that does not exist in the vector take for example the number 9 the compiler strongly protests.

the program plant with an objection « sequence contains no matching element. »

Okay but could have said sweetly.

You understood to use the « first » function must be sure that the value is, otherwise beware the wrath of the compiler.

The trick would be to use the « Any » instruction to be sure of the existence of the value of which is sought here. Once reassured we appealed to the first instruction.

Int pos = 0;

if (k.Any (b => b == 9))


k.First pos = (b => b == 9);

} Else pos = -1;

If instead you are within your rights in seeking a number that belongs to the vector example:

if (k.Any (b => b == 7))


k.First pos = (b => b == 7);

} Else pos = -1;


In this case the function returns the number 7 to inform us that the value 7 exist, it is what we already know from the « any » instruction.

The “first” function seems completely inappropriate for use with the lambda expression.

Moreover, the official example given of the use of the first function does not use the lambda expression.

First have in fact no other pretensions than to return the first element of the array.

int [] k = {2, 1, 2, 3, 5, 3, 4, 1, 6, 7, 8, 2, 1, 0, 8};

int q = k.First ();

q takes the value of 2 which is actually the first value of the vector k.

As well use our old good method

int q = k [0];

To find the first occurrence of a value in a vector it is more useful to go through the casting « tolist ».

int pos = k.ToList ().dexOf (7) ;

pos is set to 9, which is actually the rank of the value 7.

By cons if you want the value 8 which is a duplicate covering both rows 10 and 14, the program line

pos = k.ToList () .IndexOf (8);

Returns the value 10. That is to say, the first occurrence of the desired value.

You noticed the “indexof” function does not use the lambda expression.  If you persist in doing so raised an error similar to the one raised when using the lambda expression with reverse function.

the advantage with ‘indexof unlike « first » function  is that the instruction does not turn into a tizzy if the required value does not exist it gently simply return -1.

pos = k.ToList () IndexOf (9) ;





By Mohamed Ali Ettougourti


Operations on vectors or arrays  occupy the largest share of time spent on the execution of computer programs.

In sharp c # and other languages the term « lambda » is used to « standardize » some vector operations.

We give in these article basic examples:

We start by creating a vector or an array of double values

double [] x = new double [100];

To create random values we initiated a generator of random values « t » that we will use to fill the array « x » of random values.

System.Random t = new Random ();

To do this we will use the lambda expression illustrated by « => »

x = x.Select(b => b = t.NextDouble()).ToArray();

This simple line of code allows us to avoid for next loop, or do while loop or any other loops.

former code example:

for (int i = 0; i <x.length; i ++)


x [i] = t.NextDouble ();


The lambda expression also can perform some basic operations on the vector.

Thus we are able to calculate the sum of the values contained in the vector:

double sum = x.Sum();

Or to calculate the arithmetic mean:

double average = x.Average();

The same lambda expression allows us to find the maximum value in the vector:

double max = x.Max();

Or the minimum value of vector:

double min = x.Min();

we may even turning the vector on « List » to search and find the position in the vector  of the both values « min » and « max » ;

int position = x.ToList () .IndexOf (min.);

position = x.ToList () .IndexOf (max.);

The term « lambda » also helps manage elegantly and mass conversion of the values contained in the vector from one type to another.

We can easily convert double values in the vector « x »  to values of type « float » or « int » or « short » ..

We can calculate the sum of the values contained in the vector as if they were of type int32 , operating conversion and performing the addition with the lambda expression

int  int_sum = x.Select (b => System.Convert.ToInt32 (b)) Sum ();

A line of code using the command « Cast » will not work generating aerror  of type « system invalid cast exception. »

int  int_sum = x.Cast () Sum ();

with the lambda expression more advanced arithmetic  operations can be done on the values of the vector.

One can for example raise the values of the vector to the second power, determining the amount, and then divide the number by  the vector length.

All these operations take place in a single line of code

double y= x.Select(b => b * b).Sum() / x.Length;

Other uses of the lambda expression make use of words such as « next » and « index ».

This is the case if one wants to operate an accumulation on a sequence of values in the vector by using the « aggregate » function.

double yy1 = x.Where(b=> b> 0.5).Aggregate((b, next) => next + b);

When you start the program you would notice that the variable « yy » is equal to the variable « sum » and we have done nothing more than to calculate the sum of values in a different way.

But the aggregate function can regain its usefulness when using it with another statement such as « where » for example.

It will be possible soon when we calculate the sum of certain values chosen according to a specific criterion.

Code Sample:

double yy1 = x.Where(b=> b> 0.5).Aggregate((b, next) => next + b);

Checking result you would notice that only values greater than 0.5 were taken into consideration in calculating the sum.

The word « next » is not a keyword. It can be replaced in the previous line of code with the word « index » without   any results changing.

double yy2 = x.Where(b => b > 0.5).Aggregate((b, index) => index + b);

Truly the word « next » or « index » can be just as easily replaced by any other word such as « suivant » or even « cat » 🙂  without any kind of compiler protestation .

And  here is the source code of the examples given

private void sample ()

double []x = new double [100];

System.Random t = new Random();
x = x.Select(b => b = t.NextDouble()).ToArray();
double sum = x.Sum();
double average = x.Average();
double max = x.Max();
double min = x.Min();
int position = x.ToList().IndexOf(min);
position = x.ToList().IndexOf(max);

//generating error invalid cast exception
//int int_sum= x.Cast<int>().Sum();

double y= x.Select(b => b * b).Sum() / x.Length;

double yy1 = x.Where(b=> b> 0.5).Aggregate((b, next) => next + b);
double yy2 = x.Where(b => b > 0.5).Aggregate((b, suivant ) => suivant + b);

double yy2 = x.Where(b => b > 0.5).Aggregate((b, cat) => cat + b);