Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Use Lambda Expressions for Concise Code

- 07.07.26 - ErcanOPAK

⚡ Lambdas = Concise Functions

Anonymous methods are verbose. Lambda expressions are concise. One-liners for LINQ, delegates, events.

❌ Anonymous Method

Func square = 
    delegate(int x) { return x * x; };

✅ Lambda Expression

Func square = x => x * x;

📝 Lambda Syntax

// Basic syntax
(parameters) => expression
(parameters) => { statements }

// Examples
x => x * x                    // Single parameter
(x, y) => x + y              // Multiple parameters
() => DateTime.Now           // No parameters
x => { return x * x; }       // Statement lambda

// With LINQ
var adults = users.Where(u => u.Age >= 18);
var sorted = numbers.OrderBy(n => n);
var projected = users.Select(u => new { u.Name, u.Age });
var grouped = users.GroupBy(u => u.City);

// Event handlers
button.Click += (sender, e) => 
    Console.WriteLine("Button clicked");

// Func and Action
Func add = (a, b) => a + b;
Action print = s => Console.WriteLine(s);

// Expression-bodied members
public string Name => firstName + " " + lastName;
public int Sum() => a + b;

// Multiple statements
Func calculate = x =>
{
    var y = x * 2;
    return y + 5;
};

// Discard parameter
button.Click += (_, _) => HandleClick();

// Tuple returns
Func getMultiplied = x => x switch
{
    > 10 => x * 2,
    > 5 => x * 3,
    _ => x
};

🎯 Advanced Lambda Usage

// Closure
int multiplier = 5;
Func multiply = x => x * multiplier;

// Chaining
var result = numbers
    .Where(x => x > 0)
    .OrderBy(x => x)
    .Select(x => x * x)
    .ToList();

// Complex condition
var filtered = items.Where(i => 
    i.Active && 
    i.Price > 100 && 
    i.Category != "Deleted");

// Custom comparer
var sorted = items.OrderBy(i => i.Name, 
    (a, b) => a.Length.CompareTo(b.Length));

// Predicate with negation
var adults = users.Where(u => !u.IsMinor);

// Multiple conditions in LINQ
var search = items.Where(i =>
    (string.IsNullOrEmpty(searchTerm) || i.Name.Contains(searchTerm)) &&
    (minPrice == null || i.Price >= minPrice) &&
    (maxPrice == null || i.Price <= maxPrice)
);

// Expression trees (for EF)
Expression> filter = u => u.Age > 18;
var query = db.Users.Where(filter);

💡 Lambda Best Practices

  • Keep lambdas short and readable
  • Use meaningful parameter names
  • Use discard _ for unused parameters
  • Avoid side effects in expressions
  • Use with LINQ for readability

“Lambdas make code concise. Perfect for LINQ and events. Essential for modern C#.”

— C# Developer

Related posts:

Why lock(this) Is a Concurrency Time Bomb

EF Core 8 ExecuteUpdate – Batch Updates Without Loops

C#: Use CallerArgumentExpression for Better Argument Validation

Post Views: 2

Post navigation

C#: Use Generics for Type-Safe Reusable Code
Visual Studio: Use IntelliCode for AI-Assisted Development

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (597)
  • Add Constraint to SQL Table to ensure email contains @ (582)
  • Average of all values in a column that are not zero in SQL (545)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (512)
  • Find numbers with more than two decimal places in SQL (460)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com