Looping styles C# with Example



Looping styles C# with Example

While 
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 
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 loops 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 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 
list.ForEach(Console.WriteLine); 
// using an array 
Array.ForEach(myArray, Console.WriteLine); 
It is important to note that this method in only available on List 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)); 

0 Comment's

Comment Form

Submit Comment