How to Sort a List by a property in the object

前端 未结 20 2005
醉梦人生
醉梦人生 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:30

    An improved of Roger's version.

    The problem with GetDynamicSortProperty is that only get the property names but what happen if in the GridView we use NavigationProperties? it will send an exception, since it finds null.

    Example:

    "Employee.Company.Name; " will crash... since allows only "Name" as a parameter to get its value.

    Here's an improved version that allows us to sort by Navigation Properties.

    public object GetDynamicSortProperty(object item, string propName)
        {
            try
            {                 
                string[] prop = propName.Split('.'); 
    
                //Use reflection to get order type                   
                int i = 0;                    
                while (i < prop.Count())
                {
                    item = item.GetType().GetProperty(prop[i]).GetValue(item, null);
                    i++;
                }                     
    
                return item;
            }
            catch (Exception ex)
            {
                throw ex;
            }
    
    
        } 
    

提交回复
热议问题