【问题标题】:How to sort a concurrent collection in .NET 4.0如何在 .NET 4.0 中对并发集合进行排序
【发布时间】:2011-08-09 04:12:58
【问题描述】:

如何在 .NET 4.0 中对并发集合进行排序 例如,我构建了我的 ConcurrentBag 集合。如何对其中的元素进行排序?

ConcurrentBag<string> stringCollection;

ConcurrentBag<CustomType> customCollection;

【问题讨论】:

  • 您的意思是您想要一个新的排序集合,其中包含某个时间点的所有元素,还是您希望它一直被排序并按该顺序从中提取或类似的东西?
  • 我想用一种方法对其进行排序,但没有,所以我必须使用 LINQ 进行排序。

标签: c# sorting c#-4.0 concurrent-collections


【解决方案1】:

要扩展 DSW 的答案,您可以在可枚举上使用 OrderBy。

customCollection.OrderBy(cc => cc.FieldToOrderBy);

你也可以按降序来做:

customCollection.OrderByDescending(cc => cc.FieldToOrderBy);

【讨论】:

  • 可以在排序时由另一个线程更改集合吗?还是 OrderBy 创建一个新列表
  • OrderBy 只是对一个新的 IEnumerable 进行排序。底层数据结构不会改变。
【解决方案2】:

你可以使用OrderBy方法进行排序

也试试这个..

var result = stringCollection.AsParallel().AsOrdered();

更多信息请查看以下链接

http://msdn.microsoft.com/en-us/library/dd460719.aspx,您可以了解如何使用PLINQ 进行复杂排序,例如:

 var q2 = orders.AsParallel()
       .Where(o => o.OrderDate < DateTime.Parse("07/04/1997"))
       .Select(o => o)
       .OrderBy(o => o.CustomerID) // Preserve original ordering for Take operation.
       .Take(20)
       .AsUnordered()  // Remove ordering constraint to make join faster.
       .Join(
              orderDetails.AsParallel(),
              ord => ord.OrderID,
              od => od.OrderID,
              (ord, od) =>
              new
              {
                  ID = ord.OrderID,
                  Customer = ord.CustomerID,
                  Product = od.ProductID
              }
             )
       .OrderBy(i => i.Product); // Apply new ordering to final result sequence.

【讨论】:

  • 但对象仍保留在并发集合中。如何删除最旧的项目?
  • 使用 .AsParallel() 将我的执行时间减少了一半,超过 170 万个项目。很棒的提示。
【解决方案3】:

您可以使用 PLINQ,也可以编写自己的并行排序函数,如本文中的 http://www.emadomara.com/2011/08/parallel-merge-sort-using-barrier.html

【讨论】:

    【解决方案4】:

    从集合中获取一个列表,对列表进行排序,如:

    ConcurrentBag<string> bag = new ConcurrentBag<string>();
    
    var temp = bag.ToList();
    temp.Sort();//you can apply a custom sort delegate here
    
    bag = new ConcurrentBag<string>(temp);
    

    【讨论】:

    • 伙计,这是一种昂贵的方式!
    • 是的,我想是的,我只是添加了一个替代解决方案,您认为应该删除它吗?
    • 刷新页面后也看不到您的替代解决方案。无论如何,这取决于你,但我会保留这个答案。不要以为它会被否决,因为它不是无效的。
    猜你喜欢
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多