如何在.NET 4.0中对并发集合进行排序

mit*_*tel 8 c# sorting concurrent-collections c#-4.0

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

ConcurrentBag<string> stringCollection;

ConcurrentBag<CustomType> customCollection;
Run Code Online (Sandbox Code Playgroud)

Dam*_*ith 6

您可以使用OrderBy排序方法

也试试这个..

var result = stringCollection.AsParallel().AsOrdered();
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看以下链接

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.
Run Code Online (Sandbox Code Playgroud)


eva*_*nko 6

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

customCollection.OrderBy(cc => cc.FieldToOrderBy);
Run Code Online (Sandbox Code Playgroud)

您也可以按降序执行:

customCollection.OrderByDescending(cc => cc.FieldToOrderBy);
Run Code Online (Sandbox Code Playgroud)

  • OrderBy 只是对新的 IEnumerable 进行排序。底层数据结构不会改变。 (2认同)