I want an "autosort" class

J

Jeff Johnson

Unless a project particularly interests me, I'll try to see if someone else
has created what I need rather than doing it myself. Such is the case now.
I'm wondering if anyone has made a list/array class (preferrably a generic
one) that holds IComparable[<T>] objects and automatically sorts the list
when a new object is added. I know there is the SortedList<TKey, TValue>
class (and SortedDictionary), but I don't want a key/value pair; I simply
want this list to contain a value and always return those values in sorted
order. For example, I want to do this:

private SortedArray<string> mySortedArray = new SortedArray<string>();

mySortedArray.Add("Orange");
mySortedArray.Add("Peach");
mySortedArray.Add("Banana");
mySortedArray.Add("Apple");

foreach (string fruit in mySortedArray)
{
Debug.WriteLine(fruit);
}

and have the output be

Apple
Banana
Orange
Peach

without ever having to call mySortedArray.Sort() or anything like that. Has
someone done this? Am I totally blind and can't find it in the base class
library even though it's right under my nose?
 
J

Jon Skeet [C# MVP]

Jeff Johnson said:
Unless a project particularly interests me, I'll try to see if someone else
has created what I need rather than doing it myself. Such is the case now.
I'm wondering if anyone has made a list/array class (preferrably a generic
one) that holds IComparable[<T>] objects and automatically sorts the list
when a new object is added. I know there is the SortedList<TKey, TValue>
class (and SortedDictionary), but I don't want a key/value pair; I simply
want this list to contain a value and always return those values in sorted
order.

Yes, I've done it. In fact, it was doing slightly more than that - it
was keeping the length at a certain maximum too. I was picking the best
n possibilities out of *lots*, and didn't want them to all have to be
in memory.

I just started from scratch - didn't even implement all of IList<T> as
I didn't really need to. Just had an indexer, enumerator, Count, Add,
and a Last property which returned null or the last entry, depending on
whether or not it had hit the maximum value.

All I did was use BinarySearch on the (private) list in the call to
Add, in order to find the right insert point.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top