Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the List<T>.ForEach() method gone?

I started dabbling in Windows 8 metro recently, and found that one of my old buddies seems to have gone missing.

I tend to use the .ForEach() method more than I use the traditional foreach() construct, and I realized pretty quickly that this method isn't available. For example, this code will not compile under a metro app:

var list = new List<string>();

list.ForEach(System.Diagnostics.Debug.WriteLine);

I've searched to see if I could find any discussion of this, but wasn't able to. Am I just being obtuse, or is it actually gone?

like image 449
Robaticus Avatar asked Apr 24 '12 13:04

Robaticus


People also ask

Can you use ForEach on a List?

forEach statement is a C# generic statement which you can use to iterate over elements of a List.

How is ForEach implemented?

foreach isn't a function call - it's built-into the language itself, just like for loops and while loops. There's no need for it to return anything or "take" a function of any kind.


Video Answer


3 Answers

It's indeed gone:

List<T>.ForEach has been removed in Metro style apps. While the method seems simple it has a number of potential problems when the list gets mutated by the method passed to ForEach. Instead it is recommended that you simply use a foreach loop.


Wes Haggard | .NET Framework Team (BCL) | http://blogs.msdn.com/b/bclteam/

Very strangely, however, it makes an appearance in the documentation, in which nowhere does it state that this method isn't supported in .NET for Windows Store apps (formerly .NET for Metro-style apps). Perhaps this is just an oversight on part of the documentation team.

like image 67
BoltClock Avatar answered Oct 19 '22 07:10

BoltClock


To get a sense for why it might no longer be included, read this post by someone who works on the C# team at Microsoft: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

Basically, it's philosophy. The "LINQ" features are highly inspired by the functional programming paradigm, and the ForEach extension flies in the face of that... it encourages poor functional style.

Also see this answer for more details:

https://stackoverflow.com/a/529197/3043

like image 44
Joel Coehoorn Avatar answered Oct 19 '22 07:10

Joel Coehoorn


An alternative is to define it yourself of course:

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
        yield return item;
    }
}

Credit: LINQ equivalent of foreach for IEnumerable<T>

(Note: not a duplicate)

like image 16
yamen Avatar answered Oct 19 '22 07:10

yamen