简体   繁体   中英

C# Set Base Object in Derived Class

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?

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM