LINQ equivalent of foreach for IEnumerable<T>


LINQ equivalent of foreach for IEnumerable<T>



I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

IEnumerable<Item> items = GetItems(); items.ForEach(i => i.DoStuff()); 

What is the real syntax?




Generate an XSD using LinqToXml

1:



Linq - what locale/collation it uses to compare objects?
There is no ForEach extension for IEnumerable; only for List<T>.


Is there a conflict when using Data Caching and Lazy loading?
So you could do.
Rebinding GridView using LinqDataSource
items.ToList().ForEach(i => i.DoStuff()); 
Alternatively, write your own ForEach extension method:.
LINQ to DATASET update with a stored procedure
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) {     foreach(T item in enumeration)     {         action(item);     } } 


Fluent Nhibernate & Linq (Property Not Found)


Collections from LINQ to SQL and the ability to filter

2:



How do you transfer the execution of a Expression created by an IQueryable object to a IEnumerable?
Fredrik has provided the fix, but it may be worth considering why this isn't in the framework to start with.

I believe the idea is that the LINQ query operators should be side-effect-free, fitting in with a reasonably functional way of looking at the world.

Clearly ForEach is exactly the opposite - a purely side-effect-based construct.. That's not to say this is a bad thing to do - just thinking about the philosophical reasons behind the decision..


3:


You could use the FirstOrDefault() extension, which is available for IEnumerable<T>.

By returning false from the predicate, it will be run for each element but will not care that it doesn't actually find a match.

This will avoid the ToList() overhead..
IEnumerable<Item> items = GetItems(); items.FirstOrDefault(i => { i.DoStuff(); return false; }); 


4:


Update 7/17/2012: Apparently as of C# 5.0, the behavior of foreach described below has been changed and "the use of a foreach iteration variable in a nested lambda expression no longer produces unexpected results." This answer does not apply to C# ≥ 5.0.

. @John Skeet and everyone who prefers the foreach keyword.. The problem with "foreach" in C# prior to 5.0, is that it is inconsistent with how the equivalent "for comprehension" works in other languages, and with how I would expect it to work (personal opinion stated here only because others have mentioned their opinion regarding readability).

See all of the questions concerning "Access to modified closure" as well as "Closing over the loop variable considered harmful".

This is only "harmful" because of the way "foreach" is implemented in C#.. Take the following examples using the functionally equivalent extension method to that in @Fredrik Kalseth's answer..
public static class Enumerables {     public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)     {         foreach (T item in @this)         {             action(item);         }     } } 
Apologies for the overly contrived example.

I'm only using Observable because it's not entirely far fetched to do something like this.

Obviously there are better ways to create this observable, I am only attempting to demonstrate a point.

Typically the code subscribed to the observable is executed asynchronously and potentially in another thread.

If using "foreach", this could produce very strange and potentially non-deterministic results.. The following test using "ForEach" extension method passes:.
[Test] public void ForEachExtensionWin() {     //Yes, I know there is an Observable.Range. 

var values = Enumerable.Range(0, 10); var observable = Observable.Create<Func<int>>(source => { values.ForEach(value => source.OnNext(() => value)); source.OnCompleted(); return () => { }; }); //Simulate subscribing and evaluating Funcs var evaluatedObservable = observable.ToEnumerable().Select(func => func()).ToList(); //Win Assert.That(evaluatedObservable, Is.EquivalentTo(values.ToList())); }
The following fails with the error:. Expected: equivalent to < 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 > But was: < 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 >.
[Test] public void ForEachKeywordFail() {     //Yes, I know there is an Observable.Range. 

var values = Enumerable.Range(0, 10); var observable = Observable.Create<Func<int>>(source => { foreach (var value in values) { //If you have resharper, notice the warning source.OnNext(() => value); } source.OnCompleted(); return () => { }; }); //Simulate subscribing and evaluating Funcs var evaluatedObservable = observable.ToEnumerable().Select(func => func()).ToList(); //Fail Assert.That(evaluatedObservable, Is.EquivalentTo(values.ToList())); }


5:


I took Fredrik's method and modified the return type.. This way, the method supports deferred execution like other LINQ methods.. EDIT: If this wasn't clear, any usage of this method must end with ToList() or any other way to force the method to work on the complete enumerable.

Otherwise, the action would not be performed!.
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) {     foreach (T item in enumeration)     {         action(item);         yield return item;     } } 
And here's the test to help see it:.
[Test] public void TestDefferedExecutionOfIEnumerableForEach() {     IEnumerable<char> enumerable = new[] {'a', 'b', 'c'};      var sb = new StringBuilder();      enumerable         .ForEach(c => sb.Append("1"))         .ForEach(c => sb.Append("2"))         .ToList();      Assert.That(sb.ToString(), Is.EqualTo("121212")); } 
If you remove the ToList() in the end, you will see the test failing since the StringBuilder contains an empty string.

This is because no method forced the ForEach to enumerate..


6:


If you can use IQueryable<T> instead of IEnumerable<T>, then the Select method should do what you want.

.
IQueryable<Item> items = GetItems(); IQueryable<Item> modifiedItems = items.Select(i => i.DoStuff()); 
Although as Martin Harris points out, the Select() won't actually be evaluated until you enumerate the collection, so if you're relying on DoStuff() to perform some side-effect, you're better off with something like.
var modifiedItems = items.Select(i => i.DoStuff()).ToList() 
LINQ's select method doesn't really have anything in common with the SQL SELECT keyword; what it does is apply a function to each element in a set, and return a (lazy-evaluated!) set containing the results of those functions..


7:


Keep your Side Effects out of my IEnumerable

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:.
As others have pointed out here and abroad LINQ and IEnumerable methods are expected to be side-effect free.

. Do you really want to "do something" to each item in the IEnumerable? Then foreach is the best choice.

People aren't surprised when side-effects happen here.

.
foreach (var i in items) i.DoStuff(); 

I bet you don't want a side-effect

However in my experience side-effects are usually not required.

More often than not there is a simple LINQ query waiting to be discovered accompanied by a StackOverflow.com answer by either Jon Skeet, Eric Lippert, or Marc Gravell explaining how to do what you want!.

Some examples

If you are actually just aggregating (accumulating) some value then you should consider the Aggregate extension method..
items.Aggregate(initial, (acc, x) => ComputeAccumulatedValue(acc, x)); 
Perhaps you want to create a new IEnumerable from the existing values.

.
items.Select(x => Transform(x)); 
Or maybe you want to create a look-up table:.
items.ToLookup(x, x => GetTheKey(x)) 
The list (pun not entirely intended) of possibilities goes on and on.

.


8:


There is an experimental release by Microsoft of Interactive Extensions to LINQ (also on NuGet, see RxTeams's profile for more links).

The Channel 9 video explains it well.. Its docs are only provided in XML format.

I have run this documentation in Sandcastle to allow it to be in a more readable format.

Unzip the docs archive and look for index.html.. Among many other goodies, it provides the expected ForEach implementation.

It allows you to write code like this:.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };  numbers.ForEach(x => Console.WriteLine(x*x)); 


9:


As numerous answers already point out, you can easily add such an extension method yourself.

However, if you don't want to do that, although I'm not aware of anything like this in the BCL, there's still an option in the System namespace, if you already have a reference to Reactive Extension (and if you don't, you should have):.
using System.Reactive.Linq;  items.ToObservable().Subscribe(i => i.DoStuff()); 
Although the method names are a bit different, the end result is exactly what you're looking for..


10:


The purpose of ForEach is to cause side effects.

IEnumerable is for lazy enumeration of a set.. This conceptual difference is quite visible when you consider it.. SomeEnumerable.ForEach(item=>DataStore.Synchronize(item));. This wont execute until you do a "count" or a "ToList()" or something on it.

It clearly is not what is expressed.. You should use the IEnumerable extensions for setting up chains of iteration, definining content by their respective sources and conditions.

Expression Trees are powerful and efficient, but you should learn to appreciate their nature.

And not just for programming around them to save a few characters overriding lazy evaluation..


11:


Many people mentioned it, but I had to write it down.

Isn't this most clear/most readable?.
IEnumerable<Item> items = GetItems(); foreach (var item in items) item.DoStuff(); 
Short and simple(st)..


12:


According to PLINQ (available since .Net 4.0), you can do an.
IEnumerable<T>.AsParallel().ForAll()  
to do a parallel foreach loop on an IEnumerable..


13:


If you want to act as the enumeration rolls you should yield each item..
public static class EnumerableExtensions {     public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)     {         foreach (var item in enumeration)         {             action(item);             yield return item;         }     } } 


14:


Now we have the option of....
        ParallelOptions parallelOptions = new ParallelOptions();         parallelOptions.MaxDegreeOfParallelism = 4; #if DEBUG         parallelOptions.MaxDegreeOfParallelism = 1; #endif         Parallel.ForEach(bookIdList, parallelOptions, bookID => UpdateStockCount(bookID)); 
Of course, this opens up a whole new can of threadworms.. ps (Sorry about the fonts, it's what the system decided).


15:


For VB.NET you should use:.
listVariable.ForEach(Sub(i) i.Property = "Value") 


16:


Inspired by Jon Skeet, I have extended his solution with the following:. Extension Method:.
public static void Execute<TSource, TKey>(this IEnumerable<TSource> source, Action<TKey> applyBehavior, Func<TSource, TKey> keySelector) {     foreach (var item in source)     {         var target = keySelector(item);         applyBehavior(target);     } } 
Client:.
var jobs = new List<Job>()      {          new Job { Id = "XAML Developer" },          new Job { Id = "Assassin" },          new Job { Id = "Narco Trafficker" }     };  jobs.Execute(ApplyFilter, j => j.Id); 
.

.

..
    public void ApplyFilter(string filterId)     {         Debug.WriteLine(filterId);     } 


17:


I respectually disagree with the notion that link extension methods should be side-effect free (not only because they aren't, any delegate can perform side effects).. Consider the following:.
   public class Element {}     public Enum ProcessType    {       This = 0, That = 1, SomethingElse = 2    }     public class Class1    {       private Dictionary<ProcessType, Action<Element>> actions =           new Dictionary<ProcessType,Action<Element>>();        public Class1()       {          actions.Add( ProcessType.This, DoThis );          actions.Add( ProcessType.That, DoThat );          actions.Add( ProcessType.SomethingElse, DoSomethingElse );       }        // Element actions:        // This example defines 3 distict actions       // that can be applied to individual elements,       // But for the sake of the argument, make       // no assumption about how many distict       // actions there may, and that there could       // possibly be many more. 

public void DoThis( Element element ) { // Do something to element } public void DoThat( Element element ) { // Do something to element } public void DoSomethingElse( Element element ) { // Do something to element } public void Apply( ProcessType processType, IEnumerable<Element> elements ) { Action<Element> action = null; if( ! actions.TryGetValue( processType, out action ) ) throw new ArgumentException("processType"); foreach( element in elements ) action(element); } }
What the example shows is really just a kind of late-binding that allows one invoke one of many possible actions having side-effects on a sequence of elements, without having to write a big switch construct to decode the value that defines the action and translate it into its corresponding method..


18:


If you're doing this e.g.

because you need the index in your iteration, you could always use a Where construct:.
linqObject.Where((obj, index) => {   DoWork(obj, index);   return true; }).ToArray(); //MUST CALL ToArray() or ToList() or something to execute the lazy query, or the loop won't actually execute 
This has the added benefit that the original array is returned "unchanged" (the objects referenced by the list are the same, though they may not have the same data), which is often desireable in functional / chain programming methodologies like LINQ..


19:


This "functional approach" abstraction leaks big time.

Nothing on the language level prevents side effects.

As long as you can make it call your lambda/delegate for every element in the container - you will get the "ForEach" behavior.. Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites). this is a hack, and should not be used in any production code..
var b = srcDictionary.Select(                              x=>                                 {                                   destDictionary[x.Key] = x.Value;                                   return true;                                 }                              ).Count(); 


20:


What are peoples thoughts on using a method that returns itself? This is similar to the foreach solution posted above but allows Linq like chaining..
    public static IEnumerable<T> Mutate<T>(this IEnumerable<T> source, Action<T> action)     {         foreach (var item in source)         {             action(item);         }          return source;     } 
Then you can do things like.
items.Mutate(m => m.SomeProp = true) .Mutate(m => m.SomeCommand()) .Where(q => someOtherCollection.Contains(q.Id))  .Select(s => new {s.SomeOtherProp, s.SomeProp3}).LastOrDefault(); 
If you wanted to keep this true to its functional origin, perhaps you could even extend this to clone each object.
    public static IEnumerable<T> Mutate<T>(this IEnumerable<T> source, Action<T> action) where T : ICloneable     {         List<T> outList = new List<T>();         foreach (var item in source)         {             var ic = (T)item.Clone();             action(ic);             outList.Add(ic);         }          return outList;     } 


21:


ForEach can also be Chained, just put back to the pileline after the action.

remain fluent.
Employees.ForEach(e=>e.Act_A)          .ForEach(e=>e.Act_B)          .ForEach(e=>e.Act_C);  Orders  //just for demo     .ForEach(o=> o.EmailBuyer() )     .ForEach(o=> o.ProcessBilling() )     .ForEach(o=> o.ProcessShipping());   //conditional Employees     .ForEach(e=> {  if(e.Salary<1000) e.Raise(0.10);})     .ForEach(e=> {  if(e.Age   >70  ) e.Retire();}); 
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enu, Action<T> action) {     foreach (T item in enu) action(item);     return enu; // make action Chainable/Fluent } 
Edit2 above code is working, but a better version is using this.

. Edit below was a wrong example, pointed out by Taemyr.

Thanks lots.

.
Employees.ForEach(e=>e.Salary = e.Salary * 2)          .Where (e=> e.Salary > 10000)          .Average(e=> e.Salary); 
.


22:


I'm wondering why noone has responded by use of delegate function yet? In my coding I find it a far more clear and concise way of representing a subroutine you'd like to execute on iteration of a list.. NOTE: from experience, I always suggest using ToList() to avoid any issues with indexing if your original list changes, see example below:.
  public class MyObject {      public string MyString;      public int MyInt;   }    List<MyObject> list = new List<MyObject> {       new MyObject { MyString = "Test1", MyInt = 1970 },       new MyObject { MyString = "Test2", MyInt = 2010 },       new MyObject { MyString = "Test3", MyInt = 2011 },       new MyObject { MyString = "Test4", MyInt = 1767 }   };    // simple filter, but notice the Remove() will work with ToList(), remove ToList()   // and the statement will fail on execution   list.ToList().ForEach(       delegate(MyObject item) {           if (item.MyInt > 1999)               list.Remove(item);       }   ); 


23:


Yet another ForEach Example .
public static IList<AddressEntry> MapToDomain(IList<AddressModel> addresses) {     var workingAddresses = new List<AddressEntry>();      addresses.Select(a => a).ToList().ForEach(a => workingAddresses.Add(AddressModelMapper.MapToDomain(a)));      return workingAddresses; } 



68 out of 100 based on 33 user ratings 958 reviews

@