views:

2404

answers:

10

I've noticed when writing LINQ-y code that .ForEach() is a nice idiom to use. For example, here is a piece of code that takes the following inputs, and produces these outputs:

{ "One" } => "One"
{ "One", "Two" } => "One, Two"
{ "One", "Two", "Three", "Four" } => "One, Two, Three and Four";

And the code:

private string InsertCommasAttempt(IEnumerable<string> words)
{
    List<string> wordList = words.ToList();
    StringBuilder sb = new StringBuilder();
    var wordsAndSeparators = wordList.Select((string word, int pos) =>
        {
            if (pos == 0) return new { Word = word, Leading = string.Empty };
            if (pos == wordList.Count - 1) return new { Word = word, Leading = " and " };
            return new { Word = word, Leading = ", " };
        });

    wordsAndSeparators.ToList().ForEach(v => sb.Append(v.Leading).Append(v.Word));
    return sb.ToString();
}

Note the interjected .ToList() before the .ForEach() on the second to last line.

Why is it that .ForEach() isn't available as an extension method on IEnumerable? With an example like this, it just seems weird.

Thanks in advance,

Dave

+3  A: 

Because ForEach() on an IEnumerable is just a normal for each loop like this:

for each T item in MyEnumerable
{
    // Action<T> goes here
}
Joel Coehoorn
Well, I can see the appeal of embedding a lambda in a ForEach rather than doing that. But it does seem like a minor point.
Promit
Wouldn't it be nice to be able to do it inline the same way you can on a list too though? I've also wondered this in the past, but never thought to bring it up.
BenAlabaster
I guess the question is, why didn't they define .ForEach as part of the IEnumerable interface? You can foreach over other list types *or* you can use the .ForEach() method, I don't really see the difference.
BenAlabaster
Yeah, that was my thought as well.
Olema
The only real answer you will get it: because. For whatever reason, the designers decided not to add it with IEnumerable<T>. But that doesn't stop you from implementing it yourself if you wish.
Samuel
True, if you add an extension method it's pretty easy, but all you're gonna be doing is the foreach inside it which kind of defeats the purpose but whatever. :)
BenAlabaster
@balabaster: "you can foreach over list types" ... That works because those list types meet the requirements to implement IEnumerable.
Joel Coehoorn
A: 

ForEach is implemented in the concrete class List<T>

Chad Grant
It's definitely possible to add extension methods to interfaces.
Rex M
Rex to the rescue with negative comments again! yeah my stalker returns
Chad Grant
How is that a negative comment?
Rex M
@Rex: Since he edited it, you comment looks wrong. But it originally said you cannot have extension methods on interfaces, which is oh so very wrong.
Samuel
I admit I made an incorrect statement in haste and corrected it. I generally avoid extension methods because they complicate code in the same manner that operator overloads do ... they're hard to "know" they're there. So I'm not as experienced with using them.
Chad Grant
You can add extension methods to interfaces: IEnumerable<T> itself has many fine examples.
Olema
@Samuel he also seems to confuse "being wrong on questions I'm also attracted to" with "stalking" ;)
Rex M
I retracted the downvote since the answer is no longer correct btw. I try to be helpful, not actually out to get you. Promise.
Rex M
Er, *incorrect.
Rex M
I don't care about the down votes I guess. But is there an editing "etiquette"? I edit a lot. I could see someone copy / pasting correct answers just to get some easy upvotes
Chad Grant
@Deviant I've never seen that happen. It might from time to time but I imagine it's very rare. It's too easy to see who said it first, and if all you care about is rep points, enough to try to steal them, you also care enough to not want the wrath of a ton of downvotes if they catch you.
Rex M
A: 

It's called "Select" on IEnumerable<T> I am enlightened, thank you.

JP Alioto
ack! Am I wrong? Enlighten me!
JP Alioto
Not exactly - in the example above, wordsAndSeparators.Select(v =>sb.Append(v.Leading).Append(v.Word));doesn't give you what you'd expect, because of pipelining. You'd have to say: wordsAndSeparators.Select(v => sb.Append(v.Leading).Append(v.Word)).ToList();
Olema
ForEach takes an Action<T> which is a delegate that eats Ts and returns void; consequently, ForEach returns void. Select takes a Func<T, TResult> which is a delegate that eats Ts and returns TResults; consequently, Select returns an IEnumerable<TResult>.
Jason
+13  A: 

Because ForEach(Action) existed before IEnumerable<T> existed.

Since it was not added with the other extension methods, one can assume that the C# designers felt it was a bad design and prefer the foreach construct.


Edit:

If you want you can create your own extension method, it won't override the one for a List<T> but it will work for any other class which implements IEnumerable<T>.

public static class IEnumerableExtensions
{
  public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
  {
    foreach (T item in source)
      action(item);
  }
}
Samuel
That wouldn't preclude them from putting a foreach method on IEnumerable
Joel Coehoorn
No, but it shows that they feel that the method was a mistake and prefer the foreach construct.
Samuel
Either this one or the one above suffice for my answer. Thanks for the suggestion.
Olema
`action()` call inside `foreach` loop should take `item` as a parameter, not `T`.
RaYell
A: 

ForEach isn't on IList it's on List. You were using the concrete List in your example.

Joshua Belden
A: 

Just a guess, but List can iterate over its items without creating an enumerator:

public void ForEach(Action<T> action)
{
    if (action == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    for (int i = 0; i < this._size; i++)
    {
        action(this._items[i]);
    }
}

This can lead to better performance. With IEnumerable, you don't have the option to use an ordinary for-loop.

Rauhotz
In almost all cases, the performance hit will be negligible. And duh you cannot use a for loop, because IEnumerable has no concept of an index.
Samuel
It CAN make a difference. I had situations where going from 'foreach' to 'for' resulted in a speedup of 10 just because the garbage collector didn't have to collect the enumerator any more.
Rauhotz
I call BS on that. Either show proof or you're doing something very very wrong with your loops.
Samuel
@Rauhotz you must have a really shitty enumerator
Rex M
What shitty enumerator? It's the enumerator that is returned from List<T>.GetEnumerator(), an object, that has to be created and collected by the GC afterwards. Use it in a tight loop within a heavily multithreaded application and you will see the GC to take 90% of the CPU time. When using List<T>.Foreach, no object will be created and that can make the difference.
Rauhotz
+2  A: 

I am just guessing here , but putting foreach on IEnumerable would make operations on it to have side effects . None of the "available" extension methods cause side effects , putting an imperative method like foreach on there would muddy the api I guess . Also, foreach would initialize the lazy collection .

Personally I've been fending off the temptation to just add my own , just to keep side effect free functions separate from ones with side effects.

Surya
A: 

LINQ follows the pull-model and all its (extension) methods should return IEnumerable<T>, except for ToList(). The ToList() is there to end the pull-chain.

ForEach() is from the push-model world.

You can still write your own extension method to do this, as pointed out by Samuel.

taoufik
+5  A: 

According to one of the C# language designers, Eric Lippert, this is mostly for philosophical reasons. You should read the whole post, but here's the gist as far as I'm concerned:

I am philosophically opposed to providing such a method, for two reasons.

The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects.

The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.)

It does not sit well with me to make the one and only sequence operator that is only useful for its side effects.

The second reason is that doing so adds zero new representational power to the language.

fatcat1111
Wouldn't be nice if your own personal programming preferences could affect millions of others? Such power this "Eric Lippert" wields...
Frank Krueger
Yes, if only each of us could design a compiler used by millions of others :)
fatcat1111
A: 

I honestly don't know for sure why the .ForEach(Action) isn't included on IEnumerable but, right, wrong or indifferent, that's the way it is...

I DID however want to highlight the performance issue mentioned in other comments. There is a performance hit based on how you loop over a collection. It is relatively minor but nevertheless, it certainly exists. Here is an incredibly fast and sloppy code snippet to show the relations... only takes a minute or so to run through.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Start Loop timing test: loading collection...");
        List<int> l = new List<int>();

        for (long i = 0; i < 60000000; i++)
        {
            l.Add(Convert.ToInt32(i));
        }

        Console.WriteLine("Collection loaded with {0} elements: start timings",l.Count());
        Console.WriteLine("\n<===============================================>\n");
        Console.WriteLine("foreach loop test starting...");

        DateTime start = DateTime.Now;

        //l.ForEach(x => l[x].ToString());

        foreach (int x in l)
            l[x].ToString();

        Console.WriteLine("foreach Loop Time for {0} elements = {1}", l.Count(), DateTime.Now - start);
        Console.WriteLine("\n<===============================================>\n");
        Console.WriteLine("List.ForEach(x => x.action) loop test starting...");

        start = DateTime.Now;

        l.ForEach(x => l[x].ToString());

        Console.WriteLine("List.ForEach(x => x.action) Loop Time for {0} elements = {1}", l.Count(), DateTime.Now - start);
        Console.WriteLine("\n<===============================================>\n");

        Console.WriteLine("for loop test starting...");

        start = DateTime.Now;
        int count = l.Count();
        for (int i = 0; i < count; i++)
        {
            l[i].ToString();
        }

        Console.WriteLine("for Loop Time for {0} elements = {1}", l.Count(), DateTime.Now - start);
        Console.WriteLine("\n<===============================================>\n");

        Console.WriteLine("\n\nPress Enter to continue...");
        Console.ReadLine();
    }

Don't get hung up on this too much though. Performance is the currency of application design but unless your application is experiencing an actual performance hit that is causing usability problems, focus on coding for maintainability and reuse since time is the currency of real life business projects...

Aaron