Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a concurrent collection in .NET 4.0

How to sort a concurrent collection in .NET 4.0 For example I have constructed my ConcurrentBag collection. How can I sort the elements in it?

ConcurrentBag<string> stringCollection;

ConcurrentBag<CustomType> customCollection;
like image 503
mitul patel Avatar asked Aug 09 '11 04:08

mitul patel


2 Answers

To expand on DSW's answer, you can use the OrderBy on an enumerable.

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

You can also do it in descending order:

customCollection.OrderByDescending(cc => cc.FieldToOrderBy);
like image 59
evasilchenko Avatar answered Sep 20 '22 15:09

evasilchenko


you can use OrderBy method for sorting

and also try this too..

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

for more information check below link

http://msdn.microsoft.com/en-us/library/dd460719.aspx, you can lean how to do complex sorting using PLINQ, e.g:

 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.
like image 32
Damith Avatar answered Sep 20 '22 15:09

Damith