正确使用.AsParallel()有效地使用linq

时间:2015-08-01 20:14:32

标签: c# linq parallel-processing

我有一个元组,我正在使用LINQ

进行迭代
List<Tuple<string[], double[]>> tt = new List<Tuple<string[], double[]>>();

var t1 = new Tuple<string[], double[]>(
    new string[] { "java", "c#", "nn" },
    new double[] { 2, 3, 0 });

var t2 = new Tuple<string[], double[]>(
    new string[] { "java", "c#", "nn" },
    new double[] { 0, 3, 1 });

var t3 = new Tuple<string[], double[]>(
    new string[] { "java", "c#", "nn" },
    new double[] { 2, 1, 0 });

tt.Add(t1);
tt.Add(t2);
tt.Add(t3);  

var XX = (from tuples in tt
          let rows = tuples.Item2.ToArray()
          let result = rows.Select(x => x/rows.Count(i => i != 0)).ToArray()
         select new Tuple<string[], double[]>(tuples.Item1, result)
       ).ToList();

如果我想使用.Asparallel,我可以采用以下方法之一:

我可以在循环列表时添加它:

        var XX = (from tuples in tt
                  .AsParallel() //Parallel added here
                  let rows = tuples.Item2.ToArray()
                  let result = rows.Select(x => x/rows.Count(i => i != 0)).ToArray()
                 select new Tuple<string[], double[]>(tuples.Item1, result)
               ).ToList();

我可以在使用.ToArray().ToList

转换内容时添加它
        var XX = (from tuples in tt

                  let rows = tuples.Item2.ToArray()
                  let result = rows.Select(x => x / rows.Count(i => i != 0)).AsParallel().ToArray() //Parallel added right here
                 select new Tuple<string[], double[]>(tuples.Item1, result)
               ).ToList();

使用.Asparallel的最有效方法是什么?所有这些方法都没有错误,但我不确定它们是否会影响性能。

并且这样添加.Asparallel是一个坏主意吗?:

        var XX = (from tuples in tt
                  .AsParallel() //added here
                  let rows = tuples.Item2.AsParallel().ToArray() //here
                  let result = rows.Select(x => x / rows.Count(i => i != 0)).AsParallel().ToArray()//here
                 select new Tuple<string[], double[]>(tuples.Item1, result)
               ).AsParallel().ToList(); // and here

1 个答案:

答案 0 :(得分:1)

from子句中启动LINQ查询时,应添加let。这将使两个ToList语句并行执行,之后在最后调用AsParallel时将它们组合在一起。

您还可以在查询中调用Select之前添加其他var XX = (from tuples in tt.AsParallel() let rows = tuples.Item2.ToArray() let result = rows.AsParallel().Select(x => x/rows.Count(i => i != 0)).ToArray() select new Tuple<string[], double[]>(tuples.Item1, result) ).ToList();

AsParallel

但是,您应该记住YKLOI -6 01 123456789012345678901234 YKLOI -5 25 123456789012345678901234 YKLOI -4 05 123456789012345678901234 YKLOI -3 75 123456789012345678901234 YKLOI -2 83 123456789012345678901234 YKLOI -1 05 123456789012345678901234 YKLOI 0 34 123456789012345678901234 YKLOI 1 28 123456789012345678901234 YKLJW -6 87 569845874254658425485 YKLJW -5 87 569845874254658425485 ... 有一些开销,所以在某些情况下它可能比常规的非并行处理慢。取决于元素的数量和计算的成本。