Daniel complementing Maniero’s response, the Eric Lippert in 2009 he wrote a good article in his blog
, in it it explains the evils of using the List<T>.ForEach
in place of foreach
. You can read the article in full at the following link.: "foreach" vs "foreach"
Another argument would be that Micrsoft’s own architects decided not to include a method ForEach
at Linq, you can read about the subject at.: Why no Foreach method on Ienumerable interfaces
but in short, you should not use the List<T>.ForEach
, why it violates the principles of functional programming and may cause some side effects. besides, the List<T>.ForEach
is less readable and this may imply a more difficult maintenance (try debug an iteration within a List<T>.ForEach
).
Still, this is a scenario where this kind of implementation can be useful, parallelism... and yet there is a whole Namespace
for this purpose: https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(v=vs.110). aspx
var lista = Enumerable.Range(1, 10).ToList();
Parallel.ForEach(lista, (item, state, indice) => {
Console.WriteLine(string.Format("indice: {0}, value: {1}", indice, item));
});
but the implementation will still suffer from the same problem, you will not be able to modify the list, in this case you need to make use of the Parallel.For
and access the element by the index.:
var lista = Enumerable.Range(1, 10).ToList();
Parallel.For(0, lista.Count, (indice, state) => {
lista[indice] *= 2;
});
foreach(var item in lista) {
Console.WriteLine(string.Format("value: {0}", item));
}
I put in the Github for future reference.
And finally, a good reason not to use the .Select(s => s.Trim()).ToArray()
, you are not modifying the values of array. You are creating a new array with the new values, at this point you will have two arrays in memory, then will be just wasting memory, CPU cycles and forced that the Garbage Collector be called more often.
Look at this reply to understand why the Foreach does not work when you want to change a list value. It refers to Java but the same applies to C#.
– ramaral