C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we will explore lambda expressions in C#, a powerful feature that enables you to create anonymous functions concisely. Lambda expressions are particularly useful when working with LINQ (Language Integrated Query) and other scenarios that require passing a function as an argument.
A lambda expression is defined using the =>
operator, which separates the input parameters from the expression or statement block:
(input-parameters) => expression-or-statement-block
Here are some examples of lambda expressions:
x => x * x; // A lambda expression that takes an integer x and returns its square (x, y) => x + y; // A lambda expression that takes two integers x and y and returns their sum () => Console.WriteLine("Hello, world!"); // A lambda expression with no input parameters that writes a message to the console
Lambda expressions are often used with delegates. Delegates define a type for a function with a specific signature, allowing you to pass functions as arguments to other functions.
For example, suppose we have the following delegate type:
public delegate int MyOperation(int x, int y);
We can create a lambda expression that matches the delegate type and assign it to a delegate instance:
MyOperation add = (x, y) => x + y; int result = add(3, 4); // Output: 7
Lambda expressions are frequently used with LINQ to perform operations on collections. LINQ provides a set of extension methods that take delegate arguments, allowing you to pass lambda expressions to filter, sort, or transform the elements in a collection.
Here's an example using LINQ and lambda expressions to filter a list of integers:
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var evenNumbers = numbers.Where(x => x % 2 == 0); foreach (var number in evenNumbers) { Console.WriteLine(number); }
In this example, the Where
method takes a lambda expression (x => x % 2 == 0)
that filters the elements in the numbers
list, returning only the even numbers.
Lambda expressions can also be used to create event handlers. Suppose we have a simple button click event:
public event EventHandler ButtonClick;
We can create a lambda expression to handle the event when the button is clicked:
ButtonClick += (sender, args) => Console.WriteLine("Button clicked.");
This tutorial demonstrates the basics of lambda expressions in C#. Lambda expressions allow you to create anonymous functions concisely, making them particularly useful when working with delegates, LINQ, and events. By understanding and utilizing lambda expressions, you can write more flexible and expressive code.
How to use Lambda Expressions in C#
Lambda expressions provide a concise way to write anonymous methods. Here's a basic example:
// Lambda expression Func<int, int, int> add = (a, b) => a + b; // Usage int result = add(3, 4); // Result is 7
C# Lambda Expressions examples
// Simple Lambda Expression Func<int, int> square = x => x * x; // Lambda Expression with multiple parameters Func<int, int, int> add = (a, b) => a + b; // Lambda Expression with no parameters Action greet = () => Console.WriteLine("Hello, Lambda!"); // Lambda Expression with statement block Func<int, int> factorial = n => { int result = 1; for (int i = 1; i <= n; i++) result *= i; return result; };
Lambda Expressions and LINQ in C#
Lambda expressions are commonly used in LINQ queries for concise and expressive filtering, sorting, and projection.
// LINQ query using Lambda Expression var result = list.Where(x => x > 5).OrderBy(x => x).Select(x => x * 2);
Functional programming with Lambda Expressions in C#
Lambda expressions play a crucial role in functional programming paradigms, allowing functions to be treated as first-class citizens.
Func<int, int> square = x => x * x; Func<int, int, int> add = (a, b) => a + b; // Higher-order function using Lambda Func<Func<int, int, int>, int, int, int> applyOperation = (operation, x, y) => operation(x, y); int result = applyOperation(add, 3, 4); // Result is 7
Lambda Expressions in C# for filtering and sorting
// Filtering with Lambda Expression var filteredList = list.Where(x => x > 5); // Sorting with Lambda Expression var sortedList = list.OrderBy(x => x);
C# Lambda Expressions with multiple parameters
// Lambda Expression with multiple parameters Func<int, int, int> add = (a, b) => a + b;
Lambda Expressions and closures in C#
Lambda expressions can capture variables from the enclosing scope, creating closures. Example:
int multiplier = 2; Func<int, int> multiply = x => x * multiplier; int result = multiply(5); // Result is 10
Delegates and Lambda Expressions in C#
Lambda expressions are often used with delegates for concise function definitions. Example:
// Using Lambda with delegate Action<string> printMessage = message => Console.WriteLine(message);
Lambda Expressions in asynchronous programming in C#
Lambda expressions are commonly used in asynchronous programming, especially with the async
and await
keywords.
// Asynchronous Lambda Expression Func<Task<int>> asyncOperation = async () => { await Task.Delay(1000); return 42; };
Lambda Expressions in event handling in C#
Lambda expressions are frequently used for handling events in a concise manner.
// Event handling with Lambda Expression button.Click += (sender, e) => MessageBox.Show("Button clicked!");