Snipps by Patrik

Lambda expression operator (=>)

C# Lambda expression operator (=>) is a shorthand syntax for defining anonymous functions. It allows you to write compact and inline functions without the need to declare a separate method. Lambdas are commonly used in LINQ queries, event handlers, and functional programming. They improve code readability, enable concise operations on collections, and provide a flexible way to work with data and delegates.

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.

Here's an example that calculates the square of each number in a list:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> squaredNumbers = numbers.Select(x => x * x).ToList();
// squaredNumbers will be [1, 4, 9, 16, 25]

In this code, we have a list of numbers. Using the Select method and a Lambda expression x => x * x, we square each number in the list. The Lambda expression takes an input x and returns its square x * x. Finally, we have a new list squaredNumbers containing the squared values of the original numbers. Lambda expressions are versatile and enable concise operations on collections, making code more expressive and readable.


Leave a Comment

All fields are required. Your email address will not be published.