Search code examples
c#linqnomenclature

What part of the C# language is .ForEach()?


If I'm explaining the following ForEach feature to someone, is it accurate to say that #2 is the "LINQ foreach approach" or is it simply a "List<T> extension method" that is not officially associated with LINQ?

var youngCustomers = from c in customers
                     where c.Age < 30
                     select c;

//1. traditional foreach approach
foreach (var c in youngCustomers)
{
    Console.WriteLine(c.Display());
}

//2. LINQ foreach approach?
youngCustomers.ToList().ForEach(c => Console.WriteLine(c.Display()));

Solution

  • it is a normal method of List<T> though people often provide their own extension methods for other IEnumerable<T>. LINQ does not provide a ForEach extension due to its design goals of being functional/ working with immutable types, ForEach is an inherently side effect/imperative operation.