Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use parallel.ForEach to call different functions?

I have a foreach loop that runs. I am looking into Parallel functions. Is it possible to convert the following code to use parallel programming?

int result ;
int counter;
foreach(DataRow dr in ds.Tables[0].Rows) {
    switch(dr["Gender"].ToString()) {
        case "Male":
            result = functionMale(dr["Gender"].ToString());
            counter += result;
            break;
        case "Female":
            result = functionFemale(dr["Gender"].ToString());
            counter += result;
            break;
        default:
            result = functionUnkown(dr["Gender"].ToString());
            counter += result;
            break;
    }
}

Based on what I have looked into I only have the following so far.

Parallel.ForEach(ds.Tables[0].AsEnumerable(), dr => {
    var result = functionMale(dr["Gender"].ToString();
});

Any ideas? Thanks

like image 887
MrM Avatar asked Feb 21 '23 19:02

MrM


1 Answers

You could use AsParallel and Sum:

Func<string, int> calculateGender =
    gender =>
    {
        // nb: I don't know why you pass the gender to the method, but
        // I've left your intent as-is
        switch (gender)
        {
            case "Male":   return functionMale(gender);
            case "Female": return functionFemale(gender);
            default:       return functionUnknown(gender);
        }
    };

int counter = ds.Tables[0].AsEnumerable()
                          .AsParallel()
                          .Sum(dr => calculateGender(dr["Gender"].ToString()));
like image 52
user7116 Avatar answered Feb 23 '23 09:02

user7116