2011-08-09 101 views
5

如何在.NET 4.0中對併發集合進行排序例如,我構建了我的ConcurrentBag集合。我如何對其中的元素進行排序?如何在.NET 4.0中對併發集合進行排序

ConcurrentBag<string> stringCollection; 

ConcurrentBag<CustomType> customCollection; 
+2

你意味着你想要在某個時間點使用所有元素的新的排序集合,還是希望它始終按順序進行排序並按順序進行排序? – alun

+0

我想用一種方法對它進行排序,但沒有,所以我不得不使用LINQ來進行排序。 –

回答

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. 
+0

但對象保留在併發集合中。我怎樣才能刪除最古老的物品? – Kim

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); 
+0

男人,這是一個昂貴的方式來做到這一點! – tzup

+1

是的,我認爲是,我只是添加了一個替代解決方案,你認爲這應該被刪除? –

+0

刷新頁面後無法看到您的替代解決方案。無論如何,這取決於你,但我會留下這個答案。不要認爲它會被拒絕,因爲它不是無效的。 – tzup

5

要擴大DSW的回答,您可以在一個枚舉使用排序依據。

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

你也可以做降序排列:

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

集合可以被另一個線程在排序時被更改嗎?或者OrderBy創建一個新列表 –

+1

OrderBy只是對一個新的IEnumerable進行排序。底層的數據結構不會改變。 –

相關問題