search

C# Lambda Expression

Sep 03, 2024 pm 03:27 PM
c#c# tutorial

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);
}
}
}</city_details></city_details>

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);
}
}</int></int>

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!

Statement
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
C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software