Search code examples
c#parallel-processingsumienumerable

ParallelEnumerable.Sum for vectors in C#?


Is there an equivalent of ParallelEnumerable.Sum() for vectors in C#? I am currently using System.Numerics Vector2s, but really any data structure with multiple components would work fine. I am working with a very large data set that would greatly benefit from parallel sums, but right now I am having to invoke it multiple times when a single invocation would be optimal.

As an example of what I would like to accomplish -

GetWeightedValue(IEnumerable<Data> data)
{
    Vector2 sum = data.AsParallel().Select(data =>
    {
        float value = CalculateValue(data);
        float weight = CalculateWeight(data);
        return new Vector2(value * weight, weight);
    }).Sum();

    return sum.X / sum.Y;
}

Solution

  • You can simply use the ParallelEnumerable.Aggregate method from the System.Linq.Parallel package instead of Sum like so

    var data = new List<int> { 1, 2, 3, 4 };
    var sum = data.AsParallel()
        .Select(x => new Vector2(x * 2, 1))
        .Aggregate((aggregate, current) => aggregate + current);
    
    // Sum is now a Vector2(20, 4)