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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With