I have some LINQ code that under some conditions, which I can test for, benefits from parallelization. I would like to use PLINQ when such conditions apply, but also avoid to have all the processing code written twice in different places.
What I tried to do is something like this:
var list = ...
bool doParallel = ...
var listEnumerable = doParallel ? list.AsParallel() : list.AsEnumerable();
var result = listEnumerable
.Select(...);
This doesn't work though. listEnumerable is considered IEnumerable and the Select called is always Enumerable.Select, the single-thread one.
Edit: the answers in C# How to use AsParallel conditionally or attach dynamically at runtime do not answer my question because I am asking how to avoid exactly the kind of duplication suggested therein.