开发者

Linq - Is there a IEnumerable.ForEach<T> extension method that I'm missing? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Lambda Expression using Foreach Clause…

Why is there not a ForEach extension method on the IEnumerable interface?

This seems pretty basic. I'm trying to iterate over each object of an IEnumerable. It appears that I would have to cast it to a list first. Is that right? It seems to me there should be an extension method on IEnumerable that does this. I keep having to right my own and I'm getting tired of it. Am I missing it somewhere?

myEnumerable.ToList().ForEach(...)

I want to do this:

myEnumerable.ForEach(开发者_Go百科...)


Nope, there isn't a built-in ForEach extension method. It's easy enough to roll your own though:

public static class EnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (action == null) throw new ArgumentNullException("action");

        foreach (T item in source)
        {
            action(item);
        }
    }
}

But why bother? As Eric Lippert explains in this blog post, the standard foreach statement is more readable -- and philosophically more appropriate -- than a side-effecting ForEach method:

myEnumerable.ForEach(x => Console.WriteLine(x));
// vs
foreach (var x in myEnumerable) Console.WriteLine(x);


No there isn't. Eric Lippert talks about why this feature was omitted in his blog:

A number of people have asked me why there is no Microsoft-provided “ForEach” sequence operator extension method.

As a summary the two main reasons are:

  • Using ForEach violates the functional programming principles that all the other sequence operators are based upon - no side-effects.
  • A ForEach method would add no new representational power to the language. You can easily achieve the same effect more clearly using a foreach statement.


No, there is no such extension method. List<T> exposes a real method called ForEach (which has been there since .NET 2.0).


There's some talk about it here. It's not build in to the frame work, but you can roll your own extension method and use it that way. This is probably your best bet from what I can tell.

I've been in the same situation.

public static class Extensions {
  public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
    foreach (var item in source) {
      action(item);
    }
  }
}


IEnumerable do not have this extension method.

Read Eric Lippert's blog here for the reasoning behind it.

So if you need it, you will hav eto write it yourself :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜