1

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?

Konstantin
  • 461
  • 1
  • 5
  • 13
  • 1
    `ConcurrentDictionary` is not an ordered collection. Even if your code worked, it still would not guarantee that the `Keys` will be returned in the proper order in the future. You might want to look into [OrderedDictionary](https://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary(v=vs.110).aspx) and then implement your own thread-safety. Alternatively, you could build `MyDict` via [composition](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) and order the keys/elements when requested. – Rob Feb 02 '16 at 05:02

1 Answers1

3

There are at least three problems with the approach you're attempting:

  1. First and foremost, as commenter Rob points out, 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.
  2. The base identifier, like this, is read-only. You cannot assign it.
  3. The type of 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.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • Thank you very much! It seems like I will be using `SortedList`. As it is faster. Here is a comparison of the both: [When to use a SortedList over a SortedDictionary?](http://stackoverflow.com/questions/1376965/when-to-use-a-sortedlisttkey-tvalue-over-a-sorteddictionarytkey-tvalue) – Konstantin Feb 02 '16 at 05:28