What would be the best way to sort the items in a BlockingCollection<T>
based on their values in a particular order. I know there is an OrderBy
method, can it be utilized to achieve ordering?

- 157
- 1
- 14
-
Why do you need to sort it? – Dennis Mar 03 '16 at 08:55
-
1@Dennis I need to sort the Queue based on a parameter so it is not first come first serve! – Time Machine Mar 03 '16 at 08:56
-
1http://stackoverflow.com/questions/4016509/concurrent-priority-queue-in-net-4-0 – Dmitry Bychenko Mar 03 '16 at 08:58
2 Answers
It sounds like you need to order the items in the queue according to some comparison criteria. That's basically a Priority Queue
.
There is a way to use a priority queue with a BlockingCollection<T>
. You have to write a Priority Queue
that implements IProducerConsumerCollection
and pass an instance of that queue to the appropriate BlockingCollection
constructor.
Fortunately, Microsoft have provided sample code that demonstrates how to do this. It also includes the source code for a simple priority queue.
There are many other priority queue implementations available on line, for example here. You would, however, have to modify them to implement IProducerConsumerCollection
, which is unlikely to be a trivial task.
[EDIT] I found a concurrent priority queue that implements IProducerConsumerCollection
- you should be able to use it.

- 104,400
- 10
- 158
- 276
Check this https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx
From MSDN:
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void OrderByEx1()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);
foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}
}
/*
This code produces the following output:
Whiskers - 1
Boots - 4
Barley - 8
*/

- 864
- 1
- 9
- 19
-
This will sort collection snapshot, not a collection itself. Looks like OP wants some priority so proceed collection items. – Dennis Mar 03 '16 at 09:01
-
-
`BlockingCollection
` is a *concurrent* collection for solving producer-consumer tasks. Any thread can modify it in thread-safe way. Re-sorting collection, re-assigning collection at least will lead to data loss. – Dennis Mar 03 '16 at 09:07 -
-
@TimeMachine: priority queue is what you need. You've got a number of links and answer already. – Dennis Mar 03 '16 at 09:35