Reputation: 461
I have the following class:
public class MyDict: ConcurrentDictionary<int, string>
{
public GenerateContent()
{
for(int i = 0 ; i < 10 ; i++)
{
this.TryAdd(i, i.ToString());
}
base = this.OrderByDescending(v => v.Key); // --> Error
}
}
After adding some values to the base class, I would like to sort it. But ConcurrentDictionary<>
does not offer a Sort()
method. Therefore I used OrderByDescending()
. But this method does not change the original object. It returns a new one instead.
Is there a way to sort the dictionary?
Upvotes: 1
Views: 276
Reputation: 70701
There are at least three problems with the approach you're attempting:
ConcurrentDictionary<TKey, TValue>
does not preserve order. It has no mechanism for ordering, and if it did, that order wouldn't be guaranteed in the future.base
identifier, like this
, is read-only. You cannot assign it.base
would be ConcurrentDictionary<int, string>
(in your example), but the type of the OrderByDescending()
method's return value is IEnumerable<KeyValuePair<int, string>>
and so would not be assignable to the variable base
anyway.If you want an ordered dictionary, you'll need to use something else, e.g. SortedDictionary<TKey, TValue>
or SortedList<TKey, TValue>
. Of course, neither of those are thread-safe, so you would need to take additional steps to make use of them safely if they are used concurrently.
Upvotes: 3