There are a couple ways of doing this. The best one depends on your specific situation and what version of the .Net framework you are using.
If you are using .Net 3.5 or greater, then I would highly suggest that you switch to a generic
SortedDictionary class. It does all of the leg work for you and should provide all of the functionality you are after and more. Check out the link above to the MSDN documentation. It is quite in depth, including a comparison to the SortedList class which may or may not also be suitable for your application.
A basic declaration of your "Peeps" member from your example would look like this:
- //using System.Collections.Generic; SortedDictionary<int, Person> Peeps = new SortedDictionary<int, Person>();
To use the Peeps dictionary all you would do is something like this:
- Person myPerson = new Person(0);
-
Peeps.Add(myPerson.Id, myPerson);
-
If you are using a version of .Net that pre-dates 3.5, then generics are not available to you and you are left deriving your "People" class from the DictionaryBase yourself. In that case, you would have to override the "Add" and "Value" members (as well as any other property or method that adds elements to the collection) to make sure that you are maintaining a sorted dictionary. This would probably be a fairly costly procedure though. You would basically have to find where your added item would go in the sorted dictionary, remove all of the elements in the dictionary after that location, add the new item, and then add all of the other items back into the dictionary.
Generics are by far the easier solution in this case, but you are limited by framework version. Hope that helps.