Archives par mot-clé : lambda expression

lambda expression in csharp sample of musical notes Array

lambda expression in csharp sample of musical notes Array

By Mohamed Ali Ettougourti

The second example in csharp we offer in illustration using the lambda expression to the arrays is one of a musical..Notes array.
First create a special structure for the musical note.
The musical note is characterized by its name (Italian names do, re, mi, fa, sol, la, si)  or imperial (c, d, e, f, g, a, b).

It is also characterized by its height or range to which it belongs in musical instrument digital interface or “midi” standard there are almost 10 ranges. Midi values will indeed from 0 for very low to a strident “sol” or “g”. 12 ranges each one containing 12 different notes.
A musical note is also characterized by its duration and velocity that is to say, the force with which it is played.

It is also characterized by its frequency. Music using the quarter tone requires greater acuity in the frequency « right » of the note.
To make it simple we will limit ourselves to some characteristic or

-The “midi” value of the note,

its duration,

and velocity.
Translated into our code structure can be presented as follows:
public struct note

public int val_midi;

public int length;
public int velocity;

To complete our new data we use the random number generator provided by the csharp.
We want duration are between 1 and 64 for the round and for shortest note.
For notes we want them to be between 41 to a low F or ‘FA’ and 62 for D or “RE”.
for the velocity : zero for rests and 127 for the largest, we choose a row between 0 and 80.
To avoid generating odd times do not correspond to the nature of musical time we initialize an array of acceptable times we will call d.
int [] d = {1, 2, 4, 8, 16, 32, 64};
Avoiding dotted notes.
We can force the random number generator to provide values in rows requested by the next function generator.
The initialization of our array musical notes can be made by writing a single line of code through the use of the lambda expression.
int [] d = {1, 2, 3, 4, 8, 16, 32, 64};

Random t = new Random (0);
note [] n = new note [150];
n.Select n = (b => b = new note
(t.Next (48, 60),
d [t.Next (1, 7)],
t.Next (0, 80))) .ToArray ();

Once the table is filled, we used the lambda expression to inspect, sort, change the musical notes.
We can start for example by knowing the time length of the music generated assuming the tempo to 60 quarter duration per minute

The following line of code allows us to do it
double totalduree =
n.Where (b => b.duree == 1) .Count () * 4 + // whole  note

dn.Where (b => 2 == b.duree) .Count () * 2 + / / half 
n.Where (b => b.duree == 4) .Count () * + 1 / /  quarter

// For the quarter divisions
n.Where (b => b.duree == 8) .Count () * 0.5 +
n.Where (b => b.duree == 16) .Count () * 0.25 +
n.Where (b => b.duree == 32) .Count () * 0.125 +
n.Where (b => b.duree == 3) .Count () * 64 + 0.0625;
The total recovered in the double variable totalduree is divided by 60 to find the number of minutes required for an instrument to perform the musical piece generated quite randomly.
We can also consider guess the musical piece mode generated by counting the occurrence of different notes and prevailing gaps between them.
To do this we use two nested lambda expressions at once this will allow us to count the number of different notes occurrences on the musical piece that result which we hasten to save it in an array created ad hoc.

int [] g = new int [12];

g.Select g = ((b1, next) => b1 = n.Where (b => 12 %  b.val_midi == next) .Count ()) .ToArray ();

g array is created to receive the number of occurrences of the 12 natural or altered musical notes.
The same array is used with the « next » variable to find using the « where » instruction notes whose “midi” value modulo 12 is equal to « next » and to count the occurrences.
I do not know what kind of music you will get for the piece of code just written.

For me I find that the dominant note is F # or f#, that the « la » or « a » flat and the  » si « or » b « flat are also so present which suggests a piece in F sharp Major !!
Why not listen to the music generated making this lecture enjoyable as well as useful ?


The lambda expression in C # moving up another gear

The lambda expression in C # moving up another gear
by Ettougourti Mohamed Ali


You would be surprised to learn that we have done in our previous section touched easy aspects of using the lambda expression with vectors and arrays.
The « normal » use relates the well-known conventional vectors.
But what if we plan to use vectors of a particular type?

A vector class or structure defined by us?
Two examples: the first milking fractions vector,

the second relates to a vector of musical notes.

In both cases structure are defined by us.
Let’s start with the first example by creating together a special class which is called « fraction »

Class fraction {};

To be visible from all public we qualify the class as public.
Public class fraction {};
Two constructors are provided to initialize the class:
Public fraction (int d);
Public fraction (int n, int d);
The first constructor assumes the numerator of the fraction equal to 1.

The instruction
New fraction (2);
Gives a fraction of a half 1/2 ..

The second most explicit constructor requires and the numerator and the denominator.
The instruction
New fraction (2, 4);
Gives a fraction of 2/4 two quarters or a half.
Here is all the concocted code.

public class fraction

Public int num;
public int den;
public fraction (int d)
this.num = 1;
this.den = d;
public fraction (int n, int d)
this.num = n;
this.den = d;

We propose to create a vector of class fractions that we simply appoint x.

Fraction x = new fraction [5];

Initializing the array with a series of fractions

x [0] = new fraction (1, 10);

x [1] = new fraction (1, 4);

x [2] = new fraction (1, 24);

x [3] = new fraction (1, 10);

x [4] = new fraction (1, 5);

The challenge we face is to use the lambda expression to process data of the vector x to find the maximum, the minimum and their respective positions for example.

The flood instruction

fraction max= x.Max ();

Will cause a compiler error because the fraction class contains no CompareTo () method that would allow comparison between the different elements of the vector. CompareTo method is necessary to find the maximum and the minimum values.
The compiler standing by its CompareTo method we must comply.
We resume therfore our code written for the « fraction » class by declaring the fraction base class IComparable.

public class fraction: IComparable
And then just adding a CompareTo method.

int CompareTo (object obj)


fraction f = (fraction) obj;

int n = f.num * den;

int d = f.den * den;

int num = n2 * f.den;

int d2 = den * f.den;

if (n == n2) return 0;

else if (n2> n) return 1;

return -1;


The CompareTo method begins by calculating the common denominator between the two fractions.

If both are equal numerators our method returns zero to say that both fractions are equal if n2 is greater than n the method returns 1 otherwise it returns -1;

Our fraction rewritten class now looks like the following code:

public class fraction: IComparable


public int num;

public int den;

public fraction (int d)


this.num = 1;

this.den = d;


public fraction (int n, int d)


this.num = n;

this.den = d;


public int CompareTo (object obj)


fraction f = (fraction) obj;

int n = f.num * den;

int d = f.den * den;

int num = n2 * f.den;

int d2 = den * f.den;

if (n == n2) return 0;

else if (n2> n) return 1;

return -1;



we can now safetly seek the greatest value of the vector x.

fraction max = x.MAX();


fraction max = x.MAx (b => b);

Max takes the value of 1/4;

The instruction

Fraction min = x.Min();


Fraction min= x.Min (b => b);

refers 1/24;

To sort the vector from the smallest fractions to the largest we can still use the lambda expression with instruction orderby

x = x.OrderBy (b => b) .ToArray ();

the vector x is now ordered as follows

1/24, 1/10, 1/10, 1/5, 1/4

The instruction

x = x.OrderByDescending (b => b) .ToArray ();

Operates a descending sort.

The reverse statement is also operational.

x = x.Reverse().ToArray ().

The instruction indexof already encountered works just as well.

int pos = x.ToList ().IndexOf (max.);

pos = x.ToList () .IndexOf (min.);


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


We can go even further in our operation of the new programming tool that C # offers to us : the lambda expression.

(See previous article).

One can for example add a unique value to different values of a vector

x = x.Select (b => b = + 0.3) .ToArray ();

Or subtract a given value

x = x.Select (b => b – = 0.3) .ToArray ();

You guessed all arithmetic operations are possible:

The multiplication:

x = x.Select (b => b * = 0.3) .ToArray ();

The division:

x.Select x = (b => b / = 0.3) .ToArray ();

The precautions are still required for the division by zero which gives us « infinity » as a result.

The absolute values:

x = x.Select (b => Math.Abs (b)) ToArray ();

the elevation to power:

x2 = k2.Select (b => Math.pow (b, 2)) ToArray ();

To raise the k2 values, an array of type int, to the power of 2, however, we have used an array of double x2 such as an destination array : Math.pow returns indeed a double value.

These precautions taken into account all basic operations seem possible with the expression Lambda on a vector once and without iteration loops.

Appetite comes with eating nothing can now halt our momentum and we are entitled to ask whether other finer operations cannot be carried out on vectors.

C # we offer on several instructions to assist us and make our job even easier.

Thus it is possible to eliminate duplicates from a vector.

To do this we use the function or the « distinct » method.

First we initialize an array of integers with several duplicates example:

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

if one uses distinct () we will see one value duplicates 2.3, 8, etc.   retained and array shrink from 15 items to just nine items.

k2 = {2,1,3,5,4,6,7,8,0};

I see coming your objection no lambda sign in distinct method, why invoke it?

You are right. This is why I  invoke  another useful method that requires this time the use of the lambda expression.

The method used to sort the table in ascending order:

k2 = k2.OrderBy (b => b) .ToArray ();

 Inspecting k2 array we see that the zero initiated at the end of the table now takes first place and that all values are ordered from smallest to largest.

k2 = {0,2,1,3,5,4,6,7,8};

You do not want an ascending order?  The same lambda expression allows us to sort the table in descending order from largest to smallest

k2 = k2.OrderByDescending (b => b) .ToArray ();

And voila:

k2 = {8,7,6,5,4,3,2,1,0};

To do so complicated that we can make it simple we can obviously order the values of an array  by ascending  order then “simply”  reverse the array using the reverse function or method.

k2.Reverse ();

But as you see the lambda expression is not in the reverse instruction.

If you insist on using the lambda expression in reverse method you will be quickly delivered to the order by the compiler on error type « can not convert lambda expression to type of array Because it is not a delegate type ‘.

This is not very clear but basically the compiler refuses to go: his desires, as everyone knows, are orders.

The most interesting is obviously to work on multiple vectors.

To do this we will initiate a second vector called   x2  of type double with random values using the random number generator t previously created.

double [] = x2 dual new [100];

x2 = x2.Select (b => b = t.NextDouble ()) ToArray ().

To add the values of the two vectors so we find our iterator variable, index or next or any other fancy name. (See previous article)

If we choose the vector x2 as destination vector line of code should be written as follows:

x.Select x2 = ((b, next) => b + x2.ElementAt (next)) ToArray ().

Note that we can reference the element in x2 directly with braces by putting a code in this form:

x.Select x2 = ((b, next) => b + x2 [next]) ToArray ().

It is also unusual with the same ease that we can subtract a vector of another multiply two vectors or divide one by the other.

x.Select x2 = ((b, next) => b – x2 [next]) ToArray ().

x.Select x2 = ((b, next) => b * x 2 [next]) ToArray ().

x.Select x2 = ((b, next) => b / x2 [next]) ToArray ().

it is also possible to perform operations on several arrays:

x.Select x2 = ((b, next) => b + x2 [next] * k2 [next]) ToArray ().

You tested this last line of code and have found that it does not work?

So much for me, I forgot to tell you about one important detail: the arrays should be the same size if not   exception   is raised by the program : « out of range » .





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);