如何在.NET 4.0中對併發集合進行排序例如,我構建了我的ConcurrentBag集合。我如何對其中的元素進行排序?如何在.NET 4.0中對併發集合進行排序
ConcurrentBag<string> stringCollection;
ConcurrentBag<CustomType> customCollection;
如何在.NET 4.0中對併發集合進行排序例如,我構建了我的ConcurrentBag集合。我如何對其中的元素進行排序?如何在.NET 4.0中對併發集合進行排序
ConcurrentBag<string> stringCollection;
ConcurrentBag<CustomType> customCollection;
可以使用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.
但對象保留在併發集合中。我怎樣才能刪除最古老的物品? – Kim
從集合中獲取一個列表,列表進行排序,如:
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);
要擴大DSW的回答,您可以在一個枚舉使用排序依據。
customCollection.OrderBy(cc => cc.FieldToOrderBy);
你也可以做降序排列:
customCollection.OrderByDescending(cc => cc.FieldToOrderBy);
集合可以被另一個線程在排序時被更改嗎?或者OrderBy創建一個新列表 –
OrderBy只是對一個新的IEnumerable進行排序。底層的數據結構不會改變。 –
您可以使用PLINQ也可以編寫實現像一個這篇文章在自己的並行排序功能http://www.emadomara.com/2011/08/parallel-merge-sort-using-barrier.html
你意味着你想要在某個時間點使用所有元素的新的排序集合,還是希望它始終按順序進行排序並按順序進行排序? – alun
我想用一種方法對它進行排序,但沒有,所以我不得不使用LINQ來進行排序。 –