9

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

ConcurrentBag<string> stringCollection;

ConcurrentBag<CustomType> customCollection;
4

4 回答 4

8

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

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

您也可以按降序进行:

customCollection.OrderByDescending(cc => cc.FieldToOrderBy);
于 2011-08-09T04:23:10.050 回答
6

您可以使用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.
于 2011-08-09T04:18:33.767 回答
1

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

于 2011-08-12T07:30:50.853 回答
0

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

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);
于 2011-08-09T04:22:33.890 回答