Make C# ParallelEnumerable.OrderBy stable sort

≯℡__Kan透↙ 提交于 2019-12-07 07:57:19

问题


I'm sorting a list of objects by their integer ids in parallel using OrderBy. I have a few objects with the same id and need the sort to be stable.

According to Microsoft's documentation, the parallelized OrderBy is not stable, but there is an implementation approach to make it stable. However, I cannot find an example of this.

var list = new List<pair>() { new pair("a", 1), new pair("b", 1), new pair("c", 2), new pair("d", 3), new pair("e", 4) };
var newList = list.AsParallel().WithDegreeOfParallelism(4).OrderBy<pair, int>(p => p.order);

private class pair {
  private String name;
  public int order;

  public pair (String name, int order) {
    this.name = name;
    this.order = order;
  }
}

回答1:


The remarks for the other OrderBy method suggest this approach:

var newList = list
   .Select((pair, index) => new { pair, index })
   .AsParallel().WithDegreeOfParallelism(4)
   .OrderBy(p => p.pair.order)
   .ThenBy(p => p.index)
   .Select(p => p.pair);


来源:https://stackoverflow.com/questions/13709592/make-c-sharp-parallelenumerable-orderby-stable-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!