C# Lambda Expression Operator with Example – A Simple Guide
Are you struggling with writing short and clean functions in C#? Do those long function definitions drive you crazy? Don’t worry, I got your back! Today, we’re diving into C# Lambda Expression Operator with example, and trust me, it’s gonna make your coding life easier.
By the end of this lesson, you’ll be able to write functions in one line like a true coding ninja! ⚡ Plus, I’ll show you a real-world example so you can see it in action.
🔊 Sounds exciting? Let’s go! 🚀
What is a Lambda Expression?
Okay, let’s keep it super simple. A lambda expression is just a short way to write a method. Instead of creating a full function with a name, return type, and parameters, you can use lambda expressions to define them quickly in a single line.
Basic Syntax of a Lambda Expression
(parameters) => expression
The =>
is called the lambda operator.
Example 1
Let’s say we need a method that squares a numbers. Instead of writing a full method, we can use a lambda expression:
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
🎯 What’s happening here?
x => x * x;
is the Lambda Expression.- It takes
x
as input and returnsx * x
as output. - The
Func<int, int>
means this function takes an int and returns an int.
Boom! Just one line, and you have a function that squares a number! Isn’t that cool? 😎
Why Use Lambda Expressions?
Great question! Here’s why you should love them:
✔️ They make your code short and clean.
✔️ No need to define methods separately.
✔️ Works great with LINQ (you’ll love this later!).
✔️ Makes your code look professional (impress your friends! 😉).
Example 2
Let’s say we need a method that adds two numbers. Instead of writing a full method, we can use a lambda expression:
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Output: 8
(a, b)
are parameters.a + b
is the expression (logic).Func<int, int, int>
is a delegate that takes twoint
parameters and returns anint
.
Multi-line Lambda Expression
If you need multiple statements, use curly braces {}
:
Func<int, int, int> multiply = (x, y) =>
{
int result = x * y;
return result;
};
Console.WriteLine(multiply(4, 5)); // Output: 20
Here, the return
statement is used because we wrote multiple lines.
Real-World Example – Sorting Employees by Salary
Enough theory! Let’s see Lambda Expression Operator with example in C# in real life. Imagine you’re working on an HR software, and you need to sort employees by salary.
Here’s the code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<Employee> employees = new List<Employee>
{
new Employee { Name = "Alice", Salary = 5000 },
new Employee { Name = "Bob", Salary = 7000 },
new Employee { Name = "Charlie", Salary = 6000 }
};
// Sorting using Lambda Expression
var sortedEmployees = employees.OrderBy(e => e.Salary).ToList();
Console.WriteLine("Employees sorted by salary:");
foreach (var emp in sortedEmployees)
{
Console.WriteLine($"{emp.Name} - ${emp.Salary}");
}
}
}
class Employee
{
public string Name { get; set; }
public int Salary { get; set; }
}
Output:
Employees sorted by salary:
Alice - $5000
Charlie - $6000
Bob - $7000
Breaking Down the Code
- We created a list of employees with names and salaries.
- We used lambda expression
e => e.Salary
insideOrderBy()
to sort employees by salary. - Finally, we printed the sorted list.
Simple, right? Just one line of lambda magic, and our employees are sorted! 🚀
Wrapping It Up
So, what did we learn today? We explored the C# Lambda Expression Operator with example, saw why it’s awesome, and used it in a real-world scenario. Lambda expressions make coding short, sweet, and powerful. Now, it’s your turn to use them in your projects!
Oh, by the way, did you try writing your own lambda expression? 🤔 What did you create? If you got stuck, no worries! Drop your doubts, and I’d love to help. 😊
Next What?
Great job! 🎉 You’ve conquered lambda expressions like a champ. What’s next? In the next lesson, you’ll learn about Index and Range Operators. Trust me, they’re super useful for handling arrays like a pro. Stay tuned! 🚀
See you in the next lesson, buddy! 😃👨💻