
Question:
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:1
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.
Solution:2
It has nothing to do with LINQ and it's not an extension method.
ForEach
is a plain instance method on the List<T>
class.
(And if you wanted to be really nitpicky, then ForEach
is not part of the C# language at all: it's part of the .NET Base Class Library.)
Solution:3
It is not an extension method of List<T>
, it is a regular method of List<T>
.
So it has nothing to do with LINQ. If it had, the distinction between "officially associated with LINQ" and not officially associated with LINQ is not practically a very useful one. LINQ is simply a bunch of chained extension methods (often on IEnumerable<T>
). There is rarely any point in distinguishing it from other extension methods on IEnumerable<T>
. The best distinction would be that they reside in one of the System.Linq
or System.Something.Linq
namespaces.
Solution:4
It's not LINQ. One of the design aspects of LINQ is that the standard LINQ methods do not have side-effects. The ForEach method would violate this.
Eric Lippert has a blog article all about this:
http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
Solution:5
youngCustomers.ToList().ForEach(c => Console.WriteLine(c.Display()));
Let's break it down:
-
ToList
is a call toSystem.Linq.Enumerable.ToList()
introduced in .net framework 3.5 -
ForEach
is a call toSystem.Collections.Generic.List<T>.ForEach
introduced in .net framework 2.0 -
c =>
is lambda expression syntax introduced in c# 3.0.
If you look at the documentation for List<T>.ForEach
, you can see the old delegate syntax that was required back then to call it.
Solution:6
Side-effecting foreach will be ( is ) provided in Visual Studio 2010's Linq extensions.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon