Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Lambda Expressions in C#

Introduction

Lambda expressions are a concise way to represent anonymous methods using a special syntax. They are particularly useful when working with delegates, events, and LINQ queries. This tutorial will guide you through the basics of lambda expressions in C#, their syntax, and practical applications.

What is a Lambda Expression?

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. It uses the => syntax, which is known as the "goes to" operator.

The syntax for a lambda expression is:

(input parameters) => expression or statement block

Basic Syntax

Lambda expressions can be written in two forms:

  • Expression lambdas that have an expression on the right side of the => operator.
  • Statement lambdas that have a statement block on the right side of the => operator.

Here's an example of both:

Expression Lambda:

(int x, int y) => x + y

Statement Lambda:

(int x, int y) => { return x + y; }

Using Lambda Expressions with Delegates

One of the primary uses of lambda expressions is with delegates. A delegate is a type that represents references to methods with a particular parameter list and return type.

For example, consider the following delegate:

delegate int MathOperation(int a, int b);

You can use a lambda expression to create an instance of this delegate:

MathOperation add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Output: 8

Lambda Expressions and LINQ

Lambda expressions are extensively used in LINQ (Language Integrated Query) to write concise and readable queries. Here's an example of how you can use a lambda expression with LINQ:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evens = numbers.Where(n => n % 2 == 0).ToList();
Console.WriteLine(string.Join(", ", evens)); // Output: 2, 4

Capturing Variables

Lambda expressions can capture and use variables from the surrounding scope. This is called "variable capturing". For instance:

int factor = 2;
Func<int, int> multiplier = n => n * factor;
Console.WriteLine(multiplier(3)); // Output: 6

Advanced Example: Sorting with Lambda Expressions

Lambda expressions can be used to define custom sorting logic. For example, sorting a list of strings by their length:

List<string> words = new List<string> { "apple", "banana", "cherry" };
words.Sort((x, y) => x.Length.CompareTo(y.Length));
Console.WriteLine(string.Join(", ", words)); // Output: apple, cherry, banana

Conclusion

Lambda expressions are a powerful feature in C# that allow for more concise and readable code. They are particularly useful when working with delegates, events, and LINQ queries. Understanding how to use lambda expressions effectively can greatly enhance your ability to write clean and efficient C# code.