ReSharper refactored a foreach loop I had to something like this. I wanted to spawn a bunch of threads via a delegate’s BeginInvoke with different parameters, stored in a list, and store the IAsyncResults in a collection:
var asyncResults = mylist.Select(x => myDelegate.BeginInvoke(x, null, null));
My instinctive reaction is that this is not a good practice. BeginInvoke is causing a side effect of a new thread being spawned, and functions passed to Select should not cause side effects.
Or maybe it’s ok, because I’m not altering anything in the calling thread?
I think it’s hard to tell whether this is a good practice or not, it depends on how are you using it.
But the important thing to remember when using LINQ like this is that
Select()(and many other LINQ methods) doesn’t actually iterate over the collection and execute your code. That happens only when you iterate over the resulting collection, usually usingforeachorToArray().