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