2

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?

Time Machine
  • 137
  • 1
  • 11

2 Answers2

3

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.

Matthew Watson
  • 90,570
  • 7
  • 128
  • 228
-1

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
*/
Caesar
  • 719
  • 1
  • 8
  • 18
  • 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
  • Is not possible to set the ordered collection to source? – Caesar Mar 03 '16 at 09:03
  • `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
  • @Dennis what are you suggesting to do in this case Dennis? – Time Machine Mar 03 '16 at 09:28
  • @TimeMachine: priority queue is what you need. You've got a number of links and answer already. – Dennis Mar 03 '16 at 09:35