C# Lambda Expression
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.
Syntax
Now that we have understood what Lambda Expression in C# is, let us understand the standard syntax for implementing the expression. With Lambda Expression, we have two syntaxes for two types:
- Expression Lambda: This contains an input and an expression.
Syntax:
input => expression;
- Statement Lambda: This simply contains input and one of a few statements that are to be executed.
Syntax:
input => { statements };
Based on the situation, developers are free to choose which fits their needs.
How does Lambda Expression work in C#?
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.
Every lambda expression is mapped internally to an interface. Now when we execute a program with Lambda Expression, the compiler determines which interface to be assigned, based on the context of the expression, it all happens at compile time. These expressions are anonymous methods, meaning methods without names, and are implemented with the functional interface.
Examples: Now let us begin with the implementation of the lambda expression. For our first program, we will implement lambda expression in a simple form, where we use user-defined class and our second example will be pretty simple where we’ll find the first occurrence of an odd number in a list. So, let’s begin.
Code:
using System; using System.Collections.Generic; using System.Linq; class City_Details { public int cityCode { get; set; } public string cityName { get; set; } } class det { public static void Main(string[] args) { List<City_Details> details = new List<City_Details>() { new City_Details{ cityCode = 1, cityName = "Mumbai" }, new City_Details{ cityCode = 2, cityName = "Chennai" }, new City_Details{ cityCode = 3, cityName = "Pune" }, new City_Details{ cityCode = 4, cityName = "Ahmedabad" }, new City_Details{ cityCode = 5, cityName = "Delhi" } }; var newDetails = details.OrderBy(x => x.cityName); foreach(var value in newDetails) { Console.WriteLine(value.cityCode + " " + value.cityName); } } }
Code Explanation: After importing system files, we create a class with two properties as city code and cityName. Then we have our class det, with main and other functions. Here we call in our first class and assign city code and name in a form of a list. Then we list down our details list, by order, using OrderBy and here we implement the lambda expression. Now that we have listed the data in a list that goes by city name, we enter a foreach loop and print out every next line. If executed without any errors, this code will print the list, but differently, meaning the Ahmedabad, which starts with A will be printed first and Pune goes to the bottom. Refer the below-attached screenshot of the output:
As you can see, our output is as expected, alphabetically. Now, moving on to our second example, we have a simple list of numbers, which consist of odd and even numbers. So let’s understand and execute our second program.
Code:
using System; using System.Collections.Generic; class ExampleTwo { static void Main() { List<int> newList = new List<int>() { 10, 21, 31, 40 }; int oddNumber = newList.FindIndex(x => x % 2 != 0); Console.WriteLine( "\n " + oddNumber); } }
Code Explanation: This is our simplest example of Lambda Expression Implementation, where we simply use a List and Lambda Expression. Starting we System files, then our class ExampleTwo with main. We then initialized our List of Integer and in our list, we have four numbers. These are two odd and two even numbers. Next, we have our integer variable, where we use FindIndex and this is where we use Lambda Expression. Within FindIndex, we have an x, as input and our output will be a number which is not divisible by the number 2. After this math, we will have indexes of our odd numbers. And then finally we have our output statement, which will return the index number of the first occurrence of the odd number. Refer the below-attached screenshot of the output:
As we understood in the code explanation, our output will be the index number of the odd number and not the odd number itself. So here, we have 1 which is an index of 21.
Advantages
Now that we have learned almost everything about The Lambda Expression in C#, we need to understand the benefit of using it. One of the major advantages is the ability to reuse the code, then we have better readability. By not having the specify the type of input, it is one of the most flexible function.
One of the benefits is the ability to write a method for the lambda expression, just wherever we want to use it. This is best when we need to create and use a method just once. This way lot of our efforts are saved, where we don’t have to declare and write a separate method.
Conclusion
Lambda expression in any programming language can be of major use. In C#, Lambda Expression works as an anonymous expression, where is has an input on the left and expression or a list of statements on the right side. The Lambda Expression is denoted by “=>”. It’s the flexibility to have any kind of input is what makes it of great use to developers.
The above is the detailed content of C# Lambda Expression. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages such as Python. Be careful when modifying and back up the original files.
