There is a dictionary

ConcurrentDictionary<int, Man> Mans. 

Man class:

 protected class Man { protected string name; protected int age; } 

All work with the dictionary in terms of receiving data is done through the int key of the dictionary (TryGetValue). When you add a new item to the dictionary, you need to sort it by the age field of the Man object. I know about SortedDictionary, but there the sorting takes place by key, and I need to do the same thing, only by the field of the Man object. It is important to sort it when adding, and not after the fact, since the amount of data is very large. Is there any way to do this?

  • In such a data structure there can be only one person with each age value. So conceived? :) - PashaPash
  • Who to sort? Vocabulary? O_O - VladD
  • No, an abstract example), based on it, age is unique for everyone)) But in reality, this is naturally not age) - Sleeeper
  • sort exactly the dictionary. As I already wrote, there is no problem to sort VALUES at the right time and give it to the consumer, but it is very difficult. Easier to do it right away. - Sleeeper
  • Then why not keep SortedSet<Value> apart and add to it when necessary? // Yeah, that's already suggested in the answer. - VladD

1 answer 1

It is impossible to simultaneously provide an effective search by age + sorting by name within the same data structure. In databases, this problem is solved by the introduction of indexes - in fact, another Dictionary, which already stores data by name. So the easiest way for you to do is to go the same way:

  1. Declare an additional collection that will store the same elements, but already sorted by name. For example, ImmutableSortedSet with comparer by name.
  2. When adding an item, add it both to the main Dictionary and to the collection for sorting by name.
  3. If you need to - wrap it all up in your collection class, which will implement the search through the main dictionary, and as an Enumerator, but for iteration, return the Enumerator from the sorted collection.
  • Thanks for the answer! In fact, it was the first thing that came to mind - to duplicate the dictionary. However, there is a memory issue. Anyway - many thanks! - Sleeeper
  • one
    @Sleeeper objects will be stored only once - i.e. the memory you spend is only on the data structure itself, which allows you to quickly select sorted objects. It is worth taking and measuring costs in a real application. - PashaPash