C#. Examples of lambda expressions that receive as a parameters an arrays, structures, classes




Examples of lambda expressions that receive as a parameters an arrays, structures, classes

This topic is based on the topic:


Contents


Search other websites:

1. An example of a lambda expression that receives as a parameter an array of numbers

In this example, a lambda expression is declared that calculates the arithmetic mean of the array of integers.
First, we declare a delegate type

// Declaring the delegate type
// The delegate receives as a parameter an array of integers
delegate double AverageArray(int[] A);

Second, in another code (for example, an event handler), the lambda expression is programmed as follows:

// The button click event handler
private void button1_Click(object sender, EventArgs e)
{
    // Declaring a lambda expression that receives an array of integers
    // The lambda expression returns the arithmetic mean in array A
    AverageArray AA = (int[] A) =>
    {
        // calculation of the arithmetic mean in array A
        int i;
        double avg = 0;

        for (i = 0; i < A.Length; i++)
            avg += A[i];
        avg /= A.Length;
        return avg;
    };

    // Demonstration of the use of lambda-expression AA
    // Declaring an array M
    int[] M = new int[5];

    // filling the array M with values
    for (int i = 0; i < M.Length; i++)
        M[i] = i * i;

    // calling the lambda expression
    double Avg;
    Avg = AA(M); // Avg = 6
}

 

2. An example of a lambda expression that receives a structure as a parameter

In this example, a BOOK type structure is declared in the class. Then, the type of the delegate is declared, which receives a structure of BOOK type. In the event handler of the button1_Click () event, a lambda expression is declared that displays information about the contents of the structure on the form. The information is displayed in the label1, label2, label3, label4 controls of the Label type.

All program code of the module “Form1.cs”, that corresponds to the main form of the application.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TrainLyambda03
{
    public partial class Form1 : Form
    {
        // Declaring the structure in a class
        struct BOOK
        {
            public string title;
            public string author;
            public int year;
            public float price;
        };

        // Declaring the type of a delegate receiving a structure of BOOK type
        // Delegate does not receive parameters
        delegate void DisplayBOOK(BOOK B);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // A lambda expression that receives as a parameter the structure of BOOK type
            DisplayBOOK DB = (BOOK B) =>
            {
                // Output of information about the structure on the form
                label1.Text = B.author;
                label2.Text = B.title;
                label3.Text = B.year.ToString();
                label4.Text = B.price.ToString();
            };

            // variable of type 'structure'
            BOOK BB;

            BB.author = "Author";
            BB.title = "Title of book";
            BB.year = 1539;
            BB.price = 0.01f;

            // calling the lambda expression
            DB(BB);
        }
    }
}

 

3. An example of a lambda expression that receives as a parameter an array of structures

In this example, is shown the passing of an array of structures to a lambda expression. The lambda expression calculates the largest distance between two points that are stored in the array. Each element of the array is a structure of type MyPoint, which describes a point on the coordinate plane.
The program code of the module is created using the Windows Forms Application template.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TrainLyambda06
{
    public partial class Form1 : Form
    {
        // A structure that describes the coordinates of a point on the plane
        struct MyPoint
        {
            int x;
            int y;

            public int GetX() { return x; }
            public int GetY() { return y; }

            public void SetPoint(int nx, int ny)
            {
                x = nx;
                y = ny;
            }
        };

        // Declaring the type of a delegate receiving an array of 5 structures of type   MyPoint
        delegate double CalcPoints(MyPoint[] P);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Declaring a delegate-variable of type CalcPoints
            CalcPoints CP;

            // the declaration of a lambda expression that calculates the distance
            // between the two most distant points of an array of structures M
            CP = (MyPoint[] M) =>
            {
                double x1, x2, y1, y2;
                double d, maxd;

                maxd = 0;
                for (int i=0; i<M.Length-1; i++)
                    for (int j = i+1; j < M.Length; j++)
                {
                    x1 = M[i].GetX(); y1 = M[i].GetY();
                    x2 = M[j].GetX(); y2 = M[j].GetY();
                    d = Math.Sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
                    if (maxd < d) maxd = d;
                }
                return maxd;
            };

            // An array of 5 structures of MyPoint type
            MyPoint[] MP = new MyPoint[5];

            // initialization of fields of structures by some values
            for (int i = 0; i < 5; i++)
                MP[i].SetPoint(i + 1, i * 2 + 3);

            // Demonstration of the use of lambda expression
            double D;
            D = CP(MP); // D = 8.944

            label1.Text = D.ToString();
        }
    }
}

 

4. Example of a lambda expression that receives a class as an input parameter

In this example, a lambda expression is declared that displays the coordinates of the screen point x, y on the form screen. The lambda expression receives as input parameter the MyClass1 class, which implements the pixel on the monitor screen.



Passing of class in the lambda expression is the same as passing of the structure.

// The text of module MyClass1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TrainLyambda07
{
    class MyClass1
    {
        int px;
        int py;
        int color;

        public int GetX() { return px; }
        public int GetY() { return py; }
        public int GetColor() { return color; }

        public void SetXYColor(int nx, int ny, int ncolor)
        {
            px = nx;
            py = ny;
            color = ncolor;
        }
    }
}

In the Form1.cs module, you need to demonstrate passing the class to a lambda expression. For this, the type of the delegate receiving the incoming parameter MyClass1 is first declared.

// Declare the type of the delegate that receives the class as a incoming parameter
delegate void ShowInfo(MyClass1 MC);

In another method (for example, the event handler), declare the lambda expression and call it.

private void button1_Click(object sender, EventArgs e)
{
    // Declare a delegate variable of type ShowInfo and initialize it with the value of a lambda expression
    ShowInfo SI = (MyClass1 MC) =>
    {
        // output to the form of coordinates x, y
        label1.Text = MC.GetX().ToString();
        label2.Text = MC.GetY().ToString();
    };

    // demonstration of calling of lambda expression
    MyClass1 MC1;
    MC1.SetXYColor(5, 6, 11);

    // output to the form a coordinates
    SI(MC1);
}

 

5. An example of a lambda expression that receives an array of classes

In this example, a class array is passed to the lambda expression. Each class implements a point (pixel) on the monitor screen. The lambda expression computes the distance between two given points of the array. Let the class MyClass1 be declared in a separate module MyClass1.cs. This class describes the point on the monitor screen.

// The text of the module MyClass1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TrainLyambda07
{
    class MyClass1
    {
        int px;
        int py;
        int color;

        public int GetX() { return px; }
        public int GetY() { return py; }
        public int GetColor() { return color; }

        public void SetXYColor(int nx, int ny, int ncolor)
        {
            px = nx;
            py = ny;
            color = ncolor;
        }
    }
}

The delegate type is as follows:

// Declare a delegate type
delegate double CalcLength(MyClass1[] MC, int item1, int item2);

The event handler button1_Click() demonstrates the use of a lambda expression, which receives an array of classes as the input parameter. It is important here to pay attention to allocating memory for each item of the array. When you pass an array of structures, you do not need to do this, because the structures are stored as a value type, and the classes are stored as a reference type. Therefore, this link should allocate memory using the new operator.

private void button1_Click(object sender, EventArgs e)
{
    // Declare a delegate-variable of type CalcLength
    CalcLength CL;

    // Implement a lambda expression
    CL = (MC, item1, item2) =>
    {
        // output to the form of coordinates x, y
        int x1, x2, y1, y2;
        double d;
        x1 = MC[item1].GetX();
        y1 = MC[item1].GetY();
        x2 = MC[item2].GetX();
        y2 = MC[item2].GetY();
        d = Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
        return d;
    };

    // demonstration of lambda expression
    MyClass1[] MC1 = new MyClass1[5]; // allocating memory for an array of 5 classes in total

    // memory allocation for each element of the array - it is necessary for classes!!!
    for (int i = 0; i < MC1.Length; i++)
        MC1[i] = new MyClass1();

    // filling of array MC1 with arbitrary values
    for (int i = 0; i < 5; i++)
        MC1[i].SetXYColor(2 * i, 3 * i + 4, i + 3);

    // call the lambda expression
    double length;
    length = CL(MC1, 2, 3); // length = 3.6055

    // display the result on the form
    label1.Text = length.ToString();
}

 


Related topics