Question

I am using List.AsParallel().ForAll() PLINQ implementation. Inside the loop, if I find a condition is successful, I want the loop to break immediately out of the ForAll() loop. How can I achieve it?

Here is the sample code.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Basics
{
class Program
{
    class Family
    {
        public int SNo { get; set; }
        public string Name { get; set; }
    }

    static List<Family> families = null;
    static Program()
    {
        families = new List<Family>()
        {
            new Family(){SNo = 10, Name="Richard"},
            new Family(){SNo = 33, Name="Xio Fung"},
            new Family(){SNo = 10, Name="Sean"},
            new Family(){SNo = 10, Name="Andrea"},
            new Family(){SNo = 20, Name="Bjorn"},
            new Family(){SNo = 20, Name="Isabella"},
            new Family(){SNo = 35, Name="Michael"},
            new Family(){SNo = 35, Name="Marie"}
        };
    }

    private static void Main()
    {
        Dictionary<int, List<Family>> theFamily = new Dictionary<int, List<Family>>();
        var groupedFamilies = families.GroupBy(family => family.SNo);

        groupedFamilies.AsParallel().ForAll(groupedFamily =>
        {
            int groupedFamilyCount = groupedFamily.Count();
            if (groupedFamilyCount == 1)
            {
                Console.WriteLine(groupedFamily.FirstOrDefault().Name);     
                // break; <-- I want to break if I find the count = 1
            }
        });                                 
        Console.ReadLine();
    }
}    

}

Regards, Sriram

Was it helpful?

Solution

I believe Parallel.ForEach will work:

Parallel.ForEach(groupedFamilies.AsParallel(), (groupedFamily, loopState) =>
            {
                int groupedFamilyCount = groupedFamily.Count();
                if (groupedFamilyCount == 1)
                {
                    Console.WriteLine(groupedFamily.FirstOrDefault().Name);
                    loopState.Stop(); // break if I find the count = 1

                }
            });

Depending on your use case, you might need loopState.Break instead. Use Stop() for Any-like operations, Break() for First-like ones.

There's a good article on the subject in Microsoft's articles on parallel programming with .NET 4 called "When To Use Parallel For Each Or PLINQ?"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top