lambda expression in c# examples

lambda expression in c# examples
In this article [Show more]

    Practical Examples of Lambda Expressions in C#

    Lambda expressions in C# are a concise way of representing anonymous methods using a clear and concise syntax. These expressions are especially useful in LINQ queries, event handling, and wherever delegate types are required. This article will demonstrate practical examples of lambda expressions in C# across different scenarios, showing how they can simplify and streamline your coding tasks.

    Understanding Lambda Expressions

    A lambda expression in C# consists of parameters (optional), the lambda operator =>, and an expression or statement block. Here are the two main types:

    1. Expression Lambdas: Have an expression on the right side of the => and directly return a result (automatically deduced return type).
    2. Statement Lambdas: Enclosed in braces {} and can consist of multiple statements.

    Example 1: Using Lambda Expressions in LINQ

    Lambda expressions shine in LINQ (Language Integrated Query) where they are used to filter, sort, or manipulate collections efficiently.

    Filtering a List

     

    List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    var evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
    
    foreach (var num in evenNumbers)
    {
        Console.WriteLine(num); // Outputs: 2, 4, 6, 8, 10
    }
    

    Here, x => x % 2 == 0 is a lambda expression that defines the condition for filtering the list.

    Sorting a Collection

     

    List<string> names = new List<string> { "Anna", "Bill", "Clara", "David" };
    var sortedNames = names.OrderBy(name => name.Length).ToList();
    
    foreach (var name in sortedNames)
    {
        Console.WriteLine(name); // Outputs: Bill, Anna, David, Clara (based on length)
    }
    

    Example 2: Lambda Expressions as Event Handlers

    Lambda expressions can be used to handle events, making the code more concise by eliminating the need to define separate event handler methods.

     

    Button clickButton = new Button();
    clickButton.Click += (sender, e) => MessageBox.Show("Button clicked!");
    
    // The lambda expression `(sender, e) => MessageBox.Show("Button clicked!")` handles the Click event.
    

    Example 3: Using Lambda Expressions with Action and Func Delegates

    Lambda expressions can be assigned to Action or Func delegates, which are very useful for encapsulating code blocks that can be executed dynamically.

    Using Action

     

    Action<string> greet = name => Console.WriteLine($"Hello, {name}!");
    greet("Alice"); // Outputs: Hello, Alice!
    

    Using Func

     

    Func<int, int, int> multiply = (x, y) => x * y;
    Console.WriteLine(multiply(5, 2)); // Outputs: 10
    

    Example 4: Task Programming with Lambda Expressions

    Lambda expressions are incredibly useful in asynchronous programming patterns, such as when using tasks.

     

    Task.Run(() => Console.WriteLine("This runs in a separate thread."));
    

    Best Practices for Using Lambda Expressions

    1. Keep Them Short: Lambda expressions are meant to be short and concise. If your lambda gets too complex, consider refactoring it into a separate method.
    2. Use Descriptive Parameter Names: Even though lambda expressions allow for very terse code, using descriptive parameter names can make your code much easier to understand.
    3. Understand Closure Behavior: Lambda expressions capture variables from their enclosing scope. Be mindful of how these captured variables are modified to avoid unexpected behaviors, especially in multithreaded scenarios.

    Conclusion

    Lambda expressions in C# provide a powerful, flexible way to write less code while accomplishing more, whether in data manipulation, event handling, or asynchronous programming. By mastering lambda expressions, you can significantly enhance the readability and maintainability of your C# applications.

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments