C# Lambda Expression

王林
Release: 2024-09-03 15:27:19
Original
405 people have browsed it

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;
Copy after login
  • Statement Lambda: This simply contains input and one of a few statements that are to be executed.

Syntax:

input => { statements };
Copy after login

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);
}
}
}
Copy after login

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:

C# Lambda Expression

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);
}
}
Copy after login

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:

C# Lambda Expression

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!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template