[ACCEPTED]-C#: How to implement IOrderedEnumerable<T>-ienumerable

Accepted answer
Score: 13

I have a sample implementation you could look at. It's not designed 14 to be efficient by any means, but it should 13 get you started.

Basically an IOrderedEnumerable<T> just needs 12 to have an idea of its current ordering, so 11 it can create a new one. Assuming you already 10 have an IComparer<T> you build a new one by saying something 9 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 8 comparers going from the "least significant" up 7 to the "most significant". You 6 also need to put the "descending" bit 5 in there, but that's easy :)

In the sample 4 linked above, the three different aspects 3 are represented in three different classes 2 already present in MiscUtil:

  • ReverseComparer: reverses an existing IComparer<T>'s results
  • LinkedComparer: creates one comparer from two, with one master and one slave
  • ProjectionComparer: creates a comparer based on a projection from the original items to keys, delegating to another comparer to compare those keys.

Comparers are great 1 for chaining together like this.

More Related questions