Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 888
user1111380 Avatar asked Dec 22 '11 19:12

user1111380


People also ask

How do you sort ConcurrentDictionary?

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.

How do you find the value of ConcurrentDictionary?

To retrieve single item, ConcurrentDictionary provides TryGetValue method. We have to provide Key in the TryGetValue method. It takes the out parameter to return the value of key. TryGetValue returns true if key exists, or returns false if key does not exists in dictionary.

Is ConcurrentDictionary indexer thread-safe?

It is thread-safe in the sense that the internal state of the ConcurrentDictionary will not be corrupted. This is the main guarantee offered by this class.


1 Answers

Maybe not efficient if you call it often in an immutable class, but simple:

Imports System.Collections.Concurrent

Public Class SortedConcurrentDictionary(Of TKey, Tvalue)
Inherits ConcurrentDictionary(Of TKey, Tvalue)

    Shadows ReadOnly Property Values As IEnumerable(Of Tvalue)
        Get
            If MyBase.Values.Count = 0 Then
                Return MyBase.Values
            End If
            Return From k In Keys Order By k Select Me(k)
        End Get
    End Property
End Class
like image 112
smirkingman Avatar answered Nov 11 '22 21:11

smirkingman