Sort List of Dictionary using IComparer instead of OrderBy

前端 未结 1 1365
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 08:19

Following is my collection, along with data:

var data = new List>();
       data.Add(new Dictionary(         


        
相关标签:
1条回答
  • 2021-01-24 08:48

    Here is a class that you can use to chain comparers. It will accept a sequence of comparers and then to compare each item it uses each of the comparers, in order, returning the value of the first non-zero comparison, or zero if they're all zero.

    You can use this to take all of the comparers that you have and create a single comparer that you can pass to a single call to Sort or whatever you need the single comparer for.

    public class ComparerChain<T> : IComparer<T>
    {
        private IEnumerable<IComparer<T>> comparers;
        public ComparerChain(IEnumerable<IComparer<T>> comparers)
        {
            this.comparers = comparers;
        }
    
        public int Compare(T x, T y)
        {
            return comparers.Select(comparer => comparer.Compare(x, y))
                .FirstOrDefault(result => result != 0);
        }
    }
    

    On a side note, your OrderBy based method can be re-written to both only iterate the source sequence once, instead of three times, and also avoid much of the duplication:

    public static IEnumerable<Dictionary<object, object>> Sort(
        this IEnumerable<Dictionary<object, object>> data,
        IEnumerable<OrderClause> orderClauseList)
    {
        var ordered = data.OrderBy(_ => 1);
        return orderClauseList.Aggregate(ordered, (current, orderClause) =>
            (orderClause.IsAscending)
            ? current.ThenBy(d => d[orderClause.ColumnName])
            : current.ThenByDescending(d => d[orderClause.ColumnName]));
    }
    
    0 讨论(0)
提交回复
热议问题