C# Language Looping styles



The most trivial loop type. Only drawback is there is no intrinsic clue to know where you are in the loop.

/// loop while the condition satisfies
    /// do something


Similar to while, but the condition is evaluated at the end of the loop instead of the beginning. This results in executing the loops at least once.

    /// do something
} while(condition) /// loop while the condition satisfies


Another trivial loop style. While looping an index (i) gets increased and you can use it. It is usually used for handling arrays.

for ( int i = 0; i < array.Count; i++ )
    var currentItem = array[i];
    /// do something with "currentItem"


Modernized way of looping through IEnumarable objects. Good thing that you don't have to think about the index of the item or the item count of the list.

foreach ( var item in someList )
    /// do something with "item"

Foreach Method

While the other styles are used for selecting or updating the elements in collections, this style is usually used for calling a method straight away for all elements in a collection.

list.ForEach(item => item.DoSomething());

// or
list.ForEach(item => DoSomething(item));

// or using a method group

// using an array
Array.ForEach(myArray, Console.WriteLine);

It is important to note that this method in only available on List<T> instances and as a static method on Array - it is not part of Linq.

Linq Parallel Foreach

Just like Linq Foreach, except this one does the job in a parallel manner. Meaning that all the items in the collection will run the given action at the same time, simultaneously.

collection.AsParallel().ForAll(item => item.DoSomething());

/// or
collection.AsParallel().ForAll(item => DoSomething(item));