Looking for a better way to sort my List

后端 未结 7 1325
醉梦人生
醉梦人生 2021-01-02 18:37

I\'m reviewing a piece of code I wrote not too long ago, and I just hate the way I handled the sorting - I\'m wondering if anyone might be able to show me a better way.

7条回答
  •  走了就别回头了
    2021-01-02 18:56

    You could implement a custom IComparer class which uses reflection. However this would be slower.

    Here's a class, which I once used:

    class ListComparer : IComparer
    {
        private ComparerState State = ComparerState.Init;
        public string Field {get;set;}
    
    
        public int Compare(object x, object y) 
        {
            object cx;
            object cy;
    
            if (State == ComparerState.Init) 
            {
                if (x.GetType().GetProperty(pField) == null)
                    State = ComparerState.Field;
                else
                    State = ComparerState.Property;
            }
    
            if (State == ComparerState.Property) 
            {
                cx = x.GetType().GetProperty(Field).GetValue(x,null);
                cy = y.GetType().GetProperty(Field).GetValue(y,null);
            }
            else 
            {
                cx = x.GetType().GetField(Field).GetValue(x);
                cy = y.GetType().GetField(Field).GetValue(y);
            }
    
    
            if (cx == null) 
                if (cy == null)
                    return 0;
                else 
                    return -1;
            else if (cy == null)
                return 1;
    
            return ((IComparable) cx).CompareTo((IComparable) cy);
    
        }
    
        private enum ComparerState 
        {
            Init,
            Field,
            Property
        }
    }
    

    Then use it like this:

    var comparer = new ListComparer() { 
        Field= frm.SelectedSortColumn.BaseColumn.ToString() };
    if (frm.SortAscending)
        pf.Holding = pf.Holding.OrderBy(h=>h.Product, comparer).ToList();
    else
        pf.Holding = pf.Holding.OrderByDescending(h=>h.Product, comparer).ToList();
    

提交回复
热议问题