Search code examples
c#c#-4.0concurrencyparallel-processingconcurrent-programming

Sorting a ConcurrentDictionary by Value


I am able to sort my ConcurrentDictionary by value like so:

static ConcurrentDictionary<string, Proxy> Proxies = 
    new ConcurrentDictionary<string, Proxy>();

Proxies.OrderBy(p => p.Value.Speed);

Which is great, except I want to set that new re-ordered list AS the dictionary, effectively sorting the dictionary itself rather than just receiving a result list of sorted items.

I try to do something like this but had no luck - the dictionary is still unordered after:

Proxies = new ConcurrentDictionary<string,Proxy>(
    Proxies.OrderBy(p => p.Value.Speed));

It seems like doing that has no effect on the dictionary. I also tried casting the OrderBy result to a new var thinking that it may have an effect on the delegate but still no luck.

How can I re-order this ConcurrentDictionary and then force the dictionary to be the re-ordered result from OrderBy?


Solution

  • Simple dictionaries are not sorted collections. They are merely a collection which maps keys to values. ConcurrentDictionary is no different.

    You'd instead need a SortedConcurrentDictionary (akin to SortedDictionary), however, this data structure does not exist.

    As for if you actually require a sorted "dictionary", we'd need to hear more about your use case. Is this a faux priority queue? Could you simply use a ConcurrentBag<Proxy> and perform ordering after the fact?

    If you need to take the collection and in a downstream parallel method use the proxies in sorted order, I suggest taking a look at creating a custom Partitioner, potentially borrowing from the MSDN example of an OrderablePartitioner.