C# lambda expression have more than one statement?

C# lambda expression have more than one statement?

In C#, you can use lambda expressions to represent anonymous methods. When you need to include more than one statement in a lambda expression, you can use a statement block, denoted by curly braces {}. This allows you to execute multiple statements within the lambda expression.

Here's an example of how to use a lambda expression with multiple statements:

Example: Lambda Expression with Multiple Statements

Consider a scenario where you want to process a list of numbers and log each number before doubling it and adding it to a result list.

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; List<int> results = new List<int>(); // Lambda expression with multiple statements numbers.ForEach(number => { Console.WriteLine("Processing number: " + number); // Log the number int result = number * 2; // Double the number results.Add(result); // Add the result to the results list }); // Output the results Console.WriteLine("Results: " + string.Join(", ", results)); } } 

Explanation

  1. ForEach Method: The ForEach method of the List<T> class takes an Action<T> delegate as a parameter. This delegate can be represented by a lambda expression.
  2. Lambda Expression with Multiple Statements:
    • The lambda expression { number => { ... } } contains multiple statements inside the curly braces.
    • Console.WriteLine("Processing number: " + number); logs the current number.
    • int result = number * 2; calculates the double of the number.
    • results.Add(result); adds the result to the results list.

Another Example: Filtering and Transforming a List

Here's another example where we filter a list and transform it using a lambda expression with multiple statements:

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Use LINQ Where method with a lambda expression with multiple statements var evenNumbers = numbers.Where(number => { if (number % 2 == 0) { Console.WriteLine("Even number: " + number); return true; } return false; }).ToList(); // Output the even numbers Console.WriteLine("Even Numbers: " + string.Join(", ", evenNumbers)); } } 

Explanation

  1. Where Method: The Where method of IEnumerable<T> takes a Func<T, bool> delegate as a parameter.
  2. Lambda Expression with Multiple Statements:
    • The lambda expression { number => { ... } } contains multiple statements inside the curly braces.
    • if (number % 2 == 0) checks if the number is even.
    • Console.WriteLine("Even number: " + number); logs the even number.
    • return true; includes the number in the result if it is even.
    • return false; excludes the number from the result if it is not even.

These examples demonstrate how you can use lambda expressions with multiple statements in C# to perform more complex operations within a single expression.

Examples

  1. "C# lambda expression with multiple statements"

    Description: This query shows how to use multiple statements within a lambda expression by using braces {} and separating statements with semicolons.

    Code:

    using System; class Program { static void Main() { Action<int> process = x => { Console.WriteLine("Processing number: " + x); Console.WriteLine("Double the number: " + (x * 2)); }; process(5); } } 
  2. "C# lambda expression with multiple lines"

    Description: This query demonstrates how to write a lambda expression with multiple lines of code using braces.

    Code:

    using System; class Program { static void Main() { Func<int, int> calculate = x => { int square = x * x; int cube = x * x * x; return square + cube; }; Console.WriteLine(calculate(3)); // Output: 36 } } 
  3. "C# lambda expression with if statement"

    Description: This query illustrates how to use an if statement within a lambda expression.

    Code:

    using System; class Program { static void Main() { Func<int, string> classify = x => { if (x > 0) return "Positive"; else if (x < 0) return "Negative"; else return "Zero"; }; Console.WriteLine(classify(-5)); // Output: Negative } } 
  4. "C# lambda expression with for loop"

    Description: This query shows how to include a for loop within a lambda expression.

    Code:

    using System; class Program { static void Main() { Action<int> printSquares = x => { for (int i = 1; i <= x; i++) { Console.WriteLine(i * i); } }; printSquares(3); } } 
  5. "C# lambda expression with multiple operations"

    Description: This query demonstrates performing multiple operations within a lambda expression.

    Code:

    using System; class Program { static void Main() { Action<int> performOperations = x => { int square = x * x; int cube = x * x * x; Console.WriteLine($"Square: {square}, Cube: {cube}"); }; performOperations(4); } } 
  6. "C# lambda expression with switch statement"

    Description: This query illustrates how to use a switch statement within a lambda expression.

    Code:

    using System; class Program { static void Main() { Func<int, string> dayOfWeek = day => { switch (day) { case 1: return "Monday"; case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Thursday"; case 5: return "Friday"; case 6: return "Saturday"; case 7: return "Sunday"; default: return "Invalid day"; } }; Console.WriteLine(dayOfWeek(3)); // Output: Wednesday } } 
  7. "C# lambda expression with try-catch block"

    Description: This query demonstrates using a try-catch block within a lambda expression.

    Code:

    using System; class Program { static void Main() { Action<string> safePrint = text => { try { Console.WriteLine(text); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }; safePrint("Hello, world!"); } } 
  8. "C# lambda expression with nested lambdas"

    Description: This query shows how to use nested lambda expressions within the same expression.

    Code:

    using System; class Program { static void Main() { Func<int, int> complexCalculation = x => { Func<int, int> square = n => n * n; return square(x) + x; }; Console.WriteLine(complexCalculation(5)); // Output: 30 } } 
  9. "C# lambda expression with a method call"

    Description: This query demonstrates calling another method from within a lambda expression.

    Code:

    using System; class Program { static void PrintGreeting(string name) { Console.WriteLine($"Hello, {name}!"); } static void Main() { Action<string> greet = name => { PrintGreeting(name); }; greet("Jack"); } } 
  10. "C# lambda expression with return value"

    Description: This query covers how to use multiple statements in a lambda expression and return a value.

    Code:

    using System; class Program { static void Main() { Func<int, int> compute = x => { int result = x * x; return result + 10; }; Console.WriteLine(compute(6)); // Output: 46 } } 

More Tags

jmeter-5.0 digital-persona-sdk multitasking android-alarms tensorflow npm-scripts video-thumbnails guzzle6 sendkeys mms

More Programming Questions

More Tax and Salary Calculators

More Internet Calculators

More Various Measurements Units Calculators

More Animal pregnancy Calculators