C#: How to implement IOrderedEnumerable

前端 未结 2 373
北荒
北荒 2020-12-17 16:03

I want to implement some various algorithms for practice, just to see how bad I really am and to get better :p

Anyways, I thought I would try to use IEnumerabl

相关标签:
2条回答
  • 2020-12-17 16:39

    Presumably, your class will have some internal storage variable that implements IEnumerable (List<T> for example). Implementation of this method is simple in such a case:

    private List<T> data = new List<T>();
    
    public IOrderedEnumerable<CalculationResult> CreateOrderedEnumerable<TKey>(Func<CalculationResult, TKey> keySelector, IComparer<TKey> comparer, bool descending)
    {
      return descending ? 
          data.OrderByDescending(keySelector, comparer) 
        : data.OrderBy(keySelector, comparer);
    }
    
    0 讨论(0)
  • 2020-12-17 16:49

    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 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 for chaining together like this.

    0 讨论(0)
提交回复
热议问题