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
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With