How to Sort a List by a property in the object

前端 未结 20 1984
醉梦人生
醉梦人生 2020-11-21 08:25

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a l

20条回答
  •  温柔的废话
    2020-11-21 08:32

    // Totally generic sorting for use with a gridview

    public List Sort_List(string sortDirection, string sortExpression, List data)
        {
    
            List data_sorted = new List();
    
            if (sortDirection == "Ascending")
            {
                data_sorted = (from n in data
                                  orderby GetDynamicSortProperty(n, sortExpression) ascending
                                  select n).ToList();
            }
            else if (sortDirection == "Descending")
            {
                data_sorted = (from n in data
                                  orderby GetDynamicSortProperty(n, sortExpression) descending
                                  select n).ToList();
    
            }
    
            return data_sorted;
    
        }
    
        public object GetDynamicSortProperty(object item, string propName)
        {
            //Use reflection to get order type
            return item.GetType().GetProperty(propName).GetValue(item, null);
        }
    

提交回复
热议问题