| Dua Ali
A Lambda Expression in C# is an anonymous function, which contains either an expression or a bunch of statements and the operator used to implement Lambda Expression is ‘=>’. The Lambda Expression consists of two parts, out of which the left is the input while the right side part is the expression. A Simple Lambda Expression takes in an argument and does return value and one of the most common scenarios to use the lambda expression would the list.
When we implement a Lambda Expression, we have two sides and the Lambda Symbol of => in between. The left side takes an input, of any type while the right side takes an expression or a statement. In C#, Lambda Expression implements a feature, which allows our compiler to infer the variable type based on the context it is in. This feature is called the type inference feature. We can pass functions to a method call, as an argument.
Internally, every lambda expression is assigned to an interface. Now, when we run a Lambda Expression program, the compiler decides which interface to assign based on the context of the expression. This all happens at compile time. These expressions are anonymous methods, which mean they don't have a name, and they're implemented using the functional interface.Examples: Now let us begin with the implementation of the lambda expression.
using System;
using System.Collections.Generic;
using System.Linq;
class Employee
{
public string Name { get; set; }
public Designation { get; set; }
}
class test{
static void Main()
{
List employees = new List() {
new Employee { Name = "Ali", Designation=”Manager” },
new Employee { Name = "Ahmed", Designation=”Supervisor” },
new Employee { Name = "Rashid", Designation=”QA analyst” }
};
var names = employees.Select(x => x.Name); //Selects all the name from the list ‘employees’
foreach (var name in names)
{
Console.WriteLine(name); //Prints all the names in the list ‘employee’
}
Console.Read();
}
}
Code Explanation: After importing system files, we create a class with two properties as Name and Designation. Then we have our class test, with main functions. Here we call in our first class and assign name and designation in a form of a list. Then we implement lambda expression and assign all the names in the list in a variable. Now that we have listed the data in a list that goes by names, we enter a foreach loop and print out every next line.
Now taking another example, we have a list of numbers and need to find those numbers that are divisible by 2.
System;
using System.Collections.Generic;
class Test2 {
static void Main() {
List
int Divby2 = numList.FindIndex(x => x % 2 == 0);
Console.WriteLine( "\n " + Divby2);
}
}
Join us next time, as we continue our journey of learning canvas apps.Click here to learn more about Imperium's Power Apps Services. We hope this information was useful, and we look forward to sharing more insights into the Power Platform world.