For example, i have array of int and i need increase each element by 2. In modern c# with linq and extension methods the obvious solution is:
var array = new[] {1, 2, 3}; array.ForEach(p => p += 2); But unfortunately, code will not compile, because ForEach is not extension method of IEnumerable, but its a member if List. So i need to use classic foreach loop or cast array to list, but this solutions not so elegant and simple.
Can anybody tell me, why Microsoft design ForEach method as member of List, but not as extension method of IEnumerable?
Selectdoes. Not to mention thatIEnumerableis a read-only contract - you're not going to modify it anyway.ForEachextension method forIEnumerable. So it would seem that somebody at Microsoft finds value in it.ForEachis quite explicitly for side-effects - it's handy when using Rx for scheduling, for example (something likeObservable.Interval(TimeSpan.FromSeconds(1)).Take(5).ForEach(i => Console.WriteLine(i))). It also stands in contrast toSubscribe. It's adding a bit of TPL into Rx in a way.