Introduction
Lambda expressions let you write small, quick functions without naming them. They make your code shorter and easier to read.
(input_parameters) => expression_or_statement_block
x => x * x
(x, y) => x + y
(int x, int y) => { return x - y; }
() => Console.WriteLine("Hello")using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new() { 1, 2, 3, 4, 5 }; // Use lambda to filter even numbers var evens = numbers.Where(n => n % 2 == 0); Console.WriteLine("Even numbers:"); foreach (var num in evens) { Console.WriteLine(num); } // Use lambda to square numbers var squares = numbers.Select(x => x * x); Console.WriteLine("Squares:"); foreach (var sq in squares) { Console.WriteLine(sq); } } }
x => x * 2 represent in C#?x => x * 2 means a function taking input x and returning x * 2.x => x * 2 doubles input [OK](a, b) is correct.a + b without braces is valid for single expressions. (a, b) => a + b matches this.Func<int, int> square = x => x * x; Console.WriteLine(square(4));
x => x * x returns the square of the input number.square(4) returns 16.Func<int, int> add = (x, y) => x + y;
Func<int, int> expects one input parameter and one output (int).(x, y), which does not match the delegate expecting one.List<int>.Where()?var numbers = new List<int> {1, 2, 3, 4, 5, 6};
var odds = numbers.Where( /* which lambda? */ );x % 2 == 1.Pass the test and this pattern moves unknown