0
0
CsharpHow-ToBeginner · 4 min read

How to Use Lambda with List Methods in C#

In C#, you can use lambda expressions with List methods like Find, Where, and RemoveAll to specify conditions inline. Lambdas let you write short, easy-to-read code that defines how to select or modify list items without creating separate methods.
📐

Syntax

Lambda expressions are anonymous functions that you can use as arguments for List methods. The general syntax is:

list.Method(item => condition or expression)

Here:

  • list is your List object.
  • Method is a List method like Find, Where, or RemoveAll.
  • item => condition is the lambda expression where item represents each element in the list.
csharp
var numbers = new List<int> {1, 2, 3, 4, 5};
var even = numbers.Find(x => x % 2 == 0);
💻

Example

This example shows how to use lambda expressions with List methods to find, filter, and remove items:

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var fruits = new List<string> {"apple", "banana", "cherry", "date", "fig"};

        // Find the first fruit starting with 'b'
        string firstB = fruits.Find(f => f.StartsWith("b"));

        // Get all fruits with length greater than 4
        var longFruits = fruits.Where(f => f.Length > 4).ToList();

        // Remove all fruits containing the letter 'a'
        fruits.RemoveAll(f => f.Contains("a"));

        Console.WriteLine($"First fruit starting with 'b': {firstB}");
        Console.WriteLine("Fruits with length > 4: " + string.Join(", ", longFruits));
        Console.WriteLine("Fruits after removing those with 'a': " + string.Join(", ", fruits));
    }
}
Output
First fruit starting with 'b': banana Fruits with length > 4: banana, cherry Fruits after removing those with 'a': cherry, fig
⚠️

Common Pitfalls

Common mistakes when using lambdas with List methods include:

  • Using incorrect lambda syntax, like missing the => operator.
  • Confusing the parameter name inside the lambda with the list variable.
  • Forgetting to convert results to a list when using LINQ methods like Where (which returns IEnumerable).
  • Modifying the list inside a lambda in ways that cause runtime errors.
csharp
/* Wrong: missing lambda arrow */
// var result = numbers.Find(x x % 2 == 0); // Syntax error

/* Correct: */
var result = numbers.Find(x => x % 2 == 0);
📊

Quick Reference

List MethodPurposeExample Lambda Usage
FindFinds first item matching conditionlist.Find(x => x > 10)
WhereFilters items by conditionlist.Where(x => x % 2 == 0)
RemoveAllRemoves all items matching conditionlist.RemoveAll(x => x < 0)
ExistsChecks if any item matches conditionlist.Exists(x => x == 5)
ForEachPerforms action on each itemlist.ForEach(x => Console.WriteLine(x))

Key Takeaways

Use lambda expressions with List methods to write concise inline conditions.
Common List methods supporting lambdas include Find, Where, RemoveAll, Exists, and ForEach.
Always use the syntax parameter => expression inside List methods.
Remember to convert LINQ results to List if you need a List type.
Avoid syntax errors by including the lambda arrow (=>) and correct parameter usage.