How to break the execution of a for/foreach loop using the 'break' keyword.
//
// Build a list of integers
List<int> integers = new List<int>();
for (int i = 0; i <= 100; i++)
{
integers.Add(i);
}
//
// Loop the int list 50 times, and the stop:
Parallel.ForEach(integers, (int item, ParallelLoopState state) =>
{
if (item > 50)
{
Console.WriteLine("Higher than 50: {0}, exiting loop.", item);
state.Break();
}
else
{
Console.WriteLine("Less than 50: {0}", item);
}
});