linq
  1. linq-lambda-expressions

Lambda Expressions in LINQ Method Syntax

Lambda Expressions provide a concise way of writing anonymous functions in C#. LINQ Method Syntax extensively uses Lambda Expressions to represent operations executed on collections in LINQ queries.

Syntax

collection.MethodName(x => operation);

collection: the name of the collection on which the operation will be executed.

MethodName: the name of a method which is part of LINQ. E.g. Where, Select, Sum, Count, etc.

x: represents the current item in the collection.

operation: represents the expression to be evaluated on each element of the collection.

Example

Let's consider a simple example of a list of integer numbers, and we want to filter even numbers and return their sum using the LINQ method syntax.

List<int> numbers = new List<int> { 10, 20, 30, 40 };
int sumOfEvenNumbers = numbers.Where(x => x % 2 == 0).Sum();
Console.WriteLine(sumOfEvenNumbers);

Output

70

Explanation

In the above example, numbers is a collection of integers. The Where method filters only even numbers with the help of Lambda Expression x => x % 2 == 0. The Sum method returns the sum of even numbers in the collection.

Use

Lambda Expressions simplify the process of writing anonymous methods. We can use it anytime, anywhere anonymous methods are required. In LINQ Method Syntax, Lambda Expressions are used to specify filters, projections, grouping, sorting, and aggregation operation on collections.

Important Points

  • Lambda expressions can have zero or more parameters and must have a single statement enclosed in a set of curly braces or an expression.
  • Lambda expressions do not support a return statement, instead, the result is implied from the expression or the statement.
  • LINQ uses the result of one query as the input to another query.

Summary

Lambda Expressions provide a concise way of writing anonymous functions in C#. LINQ extensively uses Lambda Expressions to represent operations executed on collections in LINQ queries. In this tutorial, we saw the syntax, example, and output of Lambda Expressions used in LINQ Method Syntax. We also learned the importance of Lambda Expressions in LINQ queries, its use-cases, and important points to keep in mind while using it.

Published on: