PLINQ是否保留了序列中的原始顺序?

时间:2011-01-06 23:36:25

标签: c# plinq

PLINQ是否保证按照正在操作的原始序列的顺序返回查询结果,即使结果是并行生成的?例如:

new List<String>(){"a", "b", "c", "d"}.asParallel().Select(str => str + "a").asSequential().ToList().ForEach(str => Console.Write(str + ", ");

结果总是“aa,ba,ca,da”?

1 个答案:

答案 0 :(得分:8)

您必须使用AsOrdered()来保存订单:

        new List<String>(){"a", "b", "c", "d"}
            .AsParallel()
            .AsOrdered()
            .Select(str => str + "a")
            .AsSequential()
            .ToList()
            .ForEach(str => Console.Write(str + ", "));

另请查看:How to: Control Ordering in a PLINQ Query