Sort a List using query expressions

后端 未结 7 675
执念已碎
执念已碎 2021-02-05 15:34

I have a problem using Linq to order a structure like this :

public class Person
{
    public int ID { get; set; }
    public List Attribu         


        
7条回答
  •  囚心锁ツ
    2021-02-05 16:11

    I know this is an old post, but I thought I'd post a comparer I found a while ago in case anyone else needs it.

    public class GenericComparer : IComparer
     {
         public string SortExpression { get; set; }
         public int SortDirection { get; set; } // 0:Ascending, 1:Descending
    
         public GenericComparer(string sortExpression, int sortDirection)
         {
             this.SortExpression = sortExpression;
             this.SortDirection = sortDirection;
         }
         public GenericComparer() { }
    
         #region IComparer Members
         public int Compare(T x, T y)
         {
             PropertyInfo propertyInfo = typeof(T).GetProperty(SortExpression);
             IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
             IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
    
             if (SortDirection == 0)
             {
                 return obj1.CompareTo(obj2);
             }
             else return obj2.CompareTo(obj1);
         }
         #endregion
     }
    

    Usage

    List objectList = GetObjects(); /* from your repository or whatever */
    objectList.Sort(new GenericComparer("ObjectPropertyName", (int)SortDirection.Descending));
    dropdown.DataSource = objectList;
    dropdown.DataBind();
    

    You could overload the constructor to accept the SortDirection enum. I didn't do this because the class is in a library without a reference to System.Web.

提交回复
热议问题