使用反射排序列表

Nei*_*ir0 1 c#

我有一个表,我想为每列做排序功能.

排序有两个方向asc和desc.

1)如何使用反射对列进行排序?

List<Person> GetSortedList(List<Person> persons, string direction, string column)
{
    return persons.OrderBy(x => GetProperyByName(x, column)); //GetPropertyByName - ??
}
Run Code Online (Sandbox Code Playgroud)

2)我也想做一些我称之为linq运算符链的东西:

 List<Person> GetSortedList(List<Person> persons, string direction, string column)
    {
         var linqChain;

         if(direction=="up")
         {
             linqChain+=persons.OrderBy(x => GetProperyByName(x, column))
         }
         else
         {
             linqChain+=persons.OrderByDescending(x => GetProperyByName(x, column))
         }

         linqChain+=.Where(....);

         return linqChain.Execute();

    }
Run Code Online (Sandbox Code Playgroud)

Dea*_*alk 5

尝试这样的事情

public void SortListByPropertyName<T>(List<T> list, bool isAscending, string propertyName) where T : IComparable
{
    var propInfo = typeof (T).GetProperty(propertyName);
    Comparison<T> asc = (t1, t2) => ((IComparable) propInfo.GetValue(t1, null)).CompareTo(propInfo.GetValue(t2, null));
    Comparison<T> desc = (t1, t2) => ((IComparable) propInfo.GetValue(t2, null)).CompareTo(propInfo.GetValue(t1, null));
    list.Sort(isAscending ? asc : desc);
}
Run Code Online (Sandbox Code Playgroud)