C#: How to implement IOrderedEnumerable<T>
I have a sample implementation you could look at. It's not designed to be efficient by any means, but it should get you started.
Basically an IOrderedEnumerable<T>
just needs to have an idea of its current ordering, so it can create a new one. Assuming you already have an IComparer<T>
you build a new one by saying something like:
int Compare(T first, T second)
{
if (baseComparer != null)
{
int baseResult = baseComparer.Compare(first, second);
if (baseResult != 0)
{
return baseResult;
}
}
TKey firstKey = keySelector(first);
TKey secondKey = keySelector(second);
return comparer.Compare(firstKey, secondKey);
}
So basically you create a chain of comparers going from the "least significant" up to the "most significant". You also need to put the "descending" bit in there, but that's easy :)
In the sample linked above, the three different aspects are represented in three different classes already present in MiscUtil:
ReverseComparer
: reverses an existingIComparer<T>
's resultsLinkedComparer
: creates one comparer from two, with one master and one slaveProjectionComparer
: creates a comparer based on a projection from the original items to keys, delegating to another comparer to compare those keys.
Comparers are great for chaining together like this.