开发者

Parallelize LINQ Query with Let, Select Keywords

开发者 https://www.devze.com 2023-01-10 19:43 出处:网络
I have the following LINQ query var meshesList= ( from element i开发者_C百科n elementCoord.Elements

I have the following LINQ query

  var meshesList= (
            from element i开发者_C百科n elementCoord.Elements
                let coordinateList = elementCoord.Coordinates
                select new Plane3D
                           {
                               Pt1 = coordinateList[element.NodeList[0]], Pt2 = coordinateList[element.NodeList[1]], Pt3 = coordinateList[element.NodeList[2]]
                           }

                    into meshPlan
                    let algo = new AlgoProvider()
                    where WellBehaveMesh(meshPlan)
                    select algo.ComputeVolume(meshPlan, platformPlan)).ToList();

The from until into meshPlan will select a list of meshPlans. And this is some part that I believe parallelization can take advantage of.

Any idea on how to use PLINQ to parallelize the above operation?

I've tried the following operation:

  var meshesList= (
            (from element in elementCoord.Elements
                let coordinateList = elementCoord.Coordinates
                select new Plane3D
                           {
                               Pt1 = coordinateList[element.NodeList[0]], Pt2 = coordinateList[element.NodeList[1]], Pt3 = coordinateList[element.NodeList[2]]
                           }

                    into meshPlan).AsParallel()  //cannot compile
                    let algo = new AlgoProvider()
                    where WellBehaveMesh(meshPlan)
                    select algo.ComputeVolume(meshPlan, platformPlan)).ToList();

but sadly it cannot compile.


The simplest way of getting this to work is to break it into two query expressions:

var meshPlans = from element in elementCoord.Elements
                let coordinateList = elementCoord.Coordinates
                select new Plane3D
                {
                    Pt1 = coordinateList[element.NodeList[0]], 
                    Pt2 = coordinateList[element.NodeList[1]],
                    Pt3 = coordinateList[element.NodeList[2]]
                };

var meshesList = (from meshPlan in meshPlans.AsParallel()
                 let algo = new AlgoProvider()
                 where WellBehaveMesh(meshPlan)
                 select algo.ComputeVolume(meshPlan, platformPlan)).ToList();

Given the way query expressions (and let) work, I'm not sure you can do exactly what you want solely within a single query expression.

On the other hand, have you tried just putting AsParallel() on the first elementCoord.Elements property? That's the same loop you'd be parallelizing anyway, effectively... just a bit earlier.

0

精彩评论

暂无评论...
验证码 换一张
取 消