✨ Shield now has support for Avalonia UI

Using Lambda Expressions in C#: From Zero to Hero

Dec 10, 2023 | C#, .NET

Welcome, fellow developers! Today, we’re about to embark on an exciting journey through the incredible world of Lambda Expressions in C#. Sounds intriguing, right? So, fasten your seatbelts, put your geek glasses on, and let’s jump right in!

Understanding Lambda Expressions in C#

First things first, let’s break down these mystifying lambda expressions in C#. Before we dive into the nitty-gritty, it’s crucial to grasp leading concepts like what these beauties are and their essential role in C#. Believe it or not, they’re pretty simple!

What are Lambda Expressions in C#?

In the simplest terms, lambda expressions are anonymous functions. What’s the catch? They allow us to create methods sans the need to define a name. That’s right, no more losing sleep over what to name your next function. Here’s a basic example to kickstart things:

Func<int, int> square = x => x * x;
Console.WriteLine(square(5));  // output: 25

In the above example, x => x * x is a lambda expression. It’s as simple as that.

Basics of Lambda Expression in C#

Now, let’s dive a bit deeper into understanding the building blocks of lambda expression in C#. This information is not just good to know; it’s bread and butter for any serious C# developer.

(int x, int y) => x*y

In this example, (int x, int y) represents the parameters, => is the lambda operator, and x*y is the expression or statement block.

Lambda Expressions in Detail

Let’s leave the starting blocks as we tighten our grip on lambda expressions in C#. In this section, we’ll climb a bit higher on our Lambda Expressions proficiency ladder. We will learn how to create methods with lambda expressions, compare lambda expressions to anonymous methods, and show the power of the “Any” method in Lambda. So, are you ready to dive deeper into the lambda sea? Let’s do it!

C# Create Method with Lambda Expression

Creating methods with Lambda expressions in C# may seem confusing at first due to their terse and unconventional syntax. But once you get the hang of them, you will realize they offer a sleek and efficient way to craft your C# methods.

Let’s put to work what we learned so far about lambda expressions to define an Action delegate that represents a method with one string parameter and doesn’t return a value.

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

Now let’s use it:

greet("Stan");  // output: Hello, Stan!

Elegant, isn’t it? In the above code, name => is the lambda operator, which separates the argument name on the left from its usage on the right. We’ve passed “Stan” into the greet action delegate, leading to the output “Hello, Stan!”.

But what if we have a multi-line lambda expression? Well, you just need to enclose the expression in {} brackets. Let’s extend above example:

Action<string> greetExtended = name =>
{
    string greeting = $"Hello, {name}!";
    Console.WriteLine(greeting);
    Console.WriteLine("Nice to meet you!");
};

And call it with a name:

greetExtended("Oscar");  
/* Output: 
Hello, Oscar!
Nice to meet you!
*/

In the extended version, we added an extra line without the need to modify much of our initial structure.

Anonymous Method vs Lambda Expression in C#

You might wonder, “Why do I need lambda expressions in the first place? Can’t I accomplish the same with anonymous methods?” That’s a valid question indeed.

Yes, anonymous methods can perform similar tasks, but lambda expressions do it in a more concise and elegant manner.

Let’s define an anonymous method that does exactly what the previous lambda expressions did:

Action<string> greetAnon = delegate(string name) 
{
    string greeting = $"Hello, {name}!";
    Console.WriteLine(greeting);
};

Now let’s use it:

greetAnon("Stan");  // Output: Hello, Stan!

As you can see, anonymous methods require you to use the delegate keyword and explicitly define the parameter type (string in our example), making the syntax more verbose compared to lambda expressions.

Anonymous methods are still useful in their own right. However, lambda expressions are a more modern feature of C# and are generally preferred for their brevity and readability.

Using Any in Lambda Expression

One of the most useful and frequently used extension methods in LINQ is Any, which determines if any elements in a collection satisfy a condition. This method returns a Boolean indicating whether the specified condition is met.

Consider the following example where we have a list containing even numbers:

List<int> numbers = new List<int>() { 2, 4, 6, 8, 10 };

Now you want to quickly check if there are any odd numbers in your list. With a lambda expression, it’s a breeze:

bool hasOddNumber = numbers.Any(num => num % 2 != 0);
Console.WriteLine(hasOddNumber);  // Output: False

The Any method here uses the lambda expression num => num % 2 != 0 to check every number in the list. The expression num % 2 ! = 0 tests if a number is odd. It’s false for all our elements, hence Any returns false.

Lambda Expressions Tutorials and Explanations

Now that we’ve gotten our hands dirty with some lambda expression implementation, let’s take a breather and indulge in some cozy reading. We’ve prepared some easy-to-follow tutorials and explanations to further cement your understanding of lambda expressions in C#.

Believe it or not, the next sections will transform your C# lambda expressions journey from an empty whiteboard to a glowing matrix of knowledge, moving you closer to being a lambda expressions hero.

C# Lambda Expression Tutorial

Lambda expressions can look tricky at first, but they’re a powerful tool in your C# toolbox. And guess what? We have here a comprehensive C# lambda expression tutorial that unravels every nook and cranny, one step at a time.

In our comprehensive tutorial, we have examples like:

// defining a lambda expression
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 4));  // output: 7

This basic example underscores how a lambda expression can simplify code and make it more readable.

C# Lambda Expressions Explained

C# lambda expressions explained – sounds like music to your ears, right? In our detailed explanation, we deconstruct lambda expressions bit by bit, making it a cakewalk for even a beginner.

Advanced Usage of Lambda Expressions in C#

Welcome to the vortex of lambda expressions – the advanced usage! This section is more than just fun; it’s a chance to dive deep into lambda expressions and bear witness to their powerful capabilities. We’re going to look at some cool examples that should help stretch your understanding of how lambda expressions can be used in C#. Let’s start exploring!

Using Distinct in Lambda Expression C#

When dealing with datasets in programming, it’s not unusual to encounter duplicate data. Thanks to the function Distinct in lambda expression in C#, we can filter out duplicates, ensuring our datasets are clean and meaningful.

You might think it’s complex and hard, but in practice, it’s quite straightforward. Let’s take a simple list of integers with duplicate items as an example:

List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
IEnumerable<int> distinctNumbers = numbers.Distinct();
Console.WriteLine(string.Join(", ", distinctNumbers));  // Expected output: 1, 2, 3, 4

In the above example, we’ve used the Distinct method, which internally uses lambda expressions. This effectively removes all the duplicate elements from our list. And voila! We have a shiny, duplicate-free set of data!

How to Filter List in C# with Lambda Expression

Lambda expressions can be particularly handy when used in data filtering – one of the more common tasks in programming. Let’s say you have a list of numbers, and you want to filter out only the even numbers. This how to filter list in C# with lambda expression example should demonstrate the simplicity and power of lambda expressions:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Console.WriteLine(string.Join(", ", evenNumbers));  // Expected output: 2, 4, 6

In the above example, we’ve used a lambda expression (n => n % 2 == 0) along with the Where function to filter out and print only the even numbers from the list. Clean, quick, and efficient–that’s the beauty of lambda expressions in action!

Implementing Join in Lambda Expression C#

Often when dealing with complex sets of data, we might need to merge different collections based on a specific condition. This is where the join in lambda expression C# comes in handy.

Consider the following: We have a list of letters (A, B, C) and a list of numbers (1, 2, 3). We want to merge these two lists so that each letter is paired with the corresponding number. With a join in lambda expression, this is enormously simple:

List<string> letters = new List<string> { "A", "B", "C" };
List<int> numbers = new List<int> { 1, 2, 3 };
var joinedList = letters.Join(numbers, letter => letter, number => number.ToString(), (letter, number) => letter + number);
Console.WriteLine(string.Join(", ", joinedList));  // Expected output: A1, B2, C3

In the above example, we have used the Join function along with a lambda expression to merge two lists. The result? A newly merged list where each element is a combination of a letter and its corresponding number.

Lambda Expression as Parameter C#

Lambda expressions can also be used as parameters in method calls. This functionality allows us to build highly flexible and versatile functions. Here’s a sample about using lambda expression as parameter C#:

void PrintIf(List<int> numbers, Func<int, bool> predicate)
{
    foreach (var number in numbers)
    {
        if (predicate(number))
        {
            Console.WriteLine(number);
        }
    }
}
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
PrintIf(numbers, x => x > 5);  // Expected output: 6, 7, 8, 9, 10

The above function PrintIf takes an integer list and a Func delegate as parameters. The delegate represents a function that takes an integer and returns a boolean. Here, we are passing the lambda expression (x => x > 5) as an argument, determining the condition for numbers that should be printed.

Lambda Expression C# LINQ

If you’re familiar with C#, you’ve probably used LINQ (Language Integrated Query), which provides an SQL-like syntax and methods for querying and updating data. And guess what? Lambda expressions work brilliantly with LINQ!

Let’s see how a lambda expression C# LINQ works in our final example:

List<int> numbers = new List<int> { 1, 58, 84, 23, 56, 27, 9, 36, 4 };
IEnumerable<int> sortedNumbers = numbers.OrderBy(n => n);
Console.WriteLine(string.Join(", ", sortedNumbers));  // Expected output: 1, 4, 9, 23, 27, 36, 56, 58, 84

In this example, we used the OrderBy method of LINQ along with the lambda expression n => n to sort the numbers in ascending order.

Conclusion

So, there you have it! You’ve just traveled from the theoretical basis to the practical implementation of Lambda Expressions in C#. Now you know the what, why, and how about these useful tools.

You May Also Like