Julian Kantor
Julian Kantor

Reputation: 13

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;
}

Upvotes: 1

Views: 68

Answers (1)

MindSwipe
MindSwipe

Reputation: 7940

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)

Upvotes: 4

Related Questions