views:

2263

answers:

7

Possible Duplicate:
Linq equivalent of foreach for IEnumerable

Is there any linq style syntax for "For each" operations?

For instance, add values based on one collection to another, already existing one:

IEnumerable<int> someValues = new List<int>() { 1, 2, 3 };
IList<int> list = new List<int>();

someValues.ForEach(x => list.Add((x + 1));

Instead of

foreach(int value in someValues)
{
  list.Add(value + 1);
}
+5  A: 

Using the ToList() extenstion method is your best option:

someValues.ToList().ForEach(x => list.Add((x + 1));

There is no extenstion method in the BCL that implements ForEach directly.

Mark Seemann
Accepted because it's the first correct answer. Thanks a lot.
Stefan Steinegger
Bear in mind that this isn't ideal for a very long list, as it makes a copy of the entire list before looping through it.
Daniel Earwicker
Calling `ToList` followed by `ForEach` involves iterating through the original collection twice. I'd prefer a standard `foreach` loop any day: less typing, more readable and better performance: `foreach (var x in someValues) list.Add(x + 1);`
LukeH
For anyone who sees this and thinks its a good answer, its not. It is crazy inefficient. See Noldorin's answer for the correct way to do things.
Steve
@Steve: Thanks for pointing that out. Indeed, this is not the best solution because it means the collection is iterated over twice, and memory is temporarily allocated for the `List<T>`, adding more overhead!
Noldorin
@Stefan: Not sure how mine was not "correct". You really don't want to be using this less performant method just because it saves you writing a 3 line extension method.
Noldorin
Fair points all, but I'd like to add this: It may be inefficient in theory, but most in-memory lists I work with tend to have less than a dozen items. Perf. problems are usually somewhere else, so I think it is a premature optimization to categorically state that this answer is bad. The question was whether this *syntax* is available, and this is as close as you get on plain vanilla .NET 3.5 SP1 without writing the extension method yourself. I would love to have a ForEach extension method in the BCL, but it's not available in the current framework.
Mark Seemann
@Mark: Your code's ineffiency might be forgivable if it was more readable/understandable/intuitive than the alternatives, but it's not. What's the benefit of using your code rather than a standard `foreach` loop?
LukeH
@Luke: There's no particular benefit, but that wasn't the question either. In any case I think this is a storm in a teacup: in most cases I bet you can't feel the perf diff at all.
Mark Seemann
Yeah, I wouldn't be complaining about the performance either, if the more efficient solution weren't so very simple. (Using the foreach loop or a short extension method.) Meh, I haven't down-voted anyway.
Noldorin
A: 

There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.

Martinho Fernandes
+9  A: 

The Array and List<T> classes already have ForEach methods, though only this specific implementation. (Note that the former is static, by the way).

Not sure it really offers a great advantage over a foreach statement, but you could write an extension method to do the job for all IEnumerable<T> objects.

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

This would allow the exact code you posted in your question to work just as you want.

Noldorin
Thanks, It's clear that I could write the extension myself. I just want to use built in stuff as far as possible before doing this.
Stefan Steinegger
Yeah, that's fair enough. I also make sure I'm not reinventing BCL functionality too. In this case, there's none however.
Noldorin
+1  A: 

http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerable

aku
Oh, thanks, I didn't see this.
Stefan Steinegger
This should be posted as a comment/vote to close (duplicate), not an answer.
Noldorin
+3  A: 

There isn't anything built-in, but you can easily create your own extension method to do it:

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);
    }
}
LukeH
+1  A: 

The official MS line is "because it's not a functional operation" (ie it's a stateful operation).

Couldn't you do something like:

list.Select( x => x+1 )

or if you really need it in a List:

var someValues = new List<int>( list.Select( x => x+1 ) );
stusmith
You have a point about functional vs. stateful operations. However, F# was designed as a functional length, and has an equivalent `ForEach` method.
Noldorin
A: 

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
{
    list.Add(x + 1);
}

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
   foreach (var x in @this)
      action(x);
}
dustyburwell