Looping styles

suggest change

While

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

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

Do

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

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

For

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"
}

Foreach

Modernized way of looping through IEnumerable 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
list.ForEach(Console.WriteLine);

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

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

PLINQ ForAll

Like List<T>.ForEach, except this one does the job in parallel. The action may run for several items at the same time, up to the degree of parallelism.

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

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents