开发者

Sorting list using reflection

I have a table and i want to do sorting function for each column.

Sorting has two direction asc and desc.

1) How can i sort columns using reflection?

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

2) Also i want to do something what i can call chain of linq operators:

 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 =&g开发者_JAVA百科t; GetProperyByName(x, column))
         }

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

         return linqChain.Execute();

    }


try something like this

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);
}


1) If you want to sort using string names of columns, use the Dynamic LINQ library.

if (direction == "ASC")    
    return persons.OrderBy(column);
else
    return persons.OrderByDescending(column);

2) You can concatenate LINQ expressions together by using an expression object.

Expression linqChain = persons;

if (direction == "up")
{
    linqChain = linqChain.OrderBy(column);
}
else
{
    linqChain = linqChain.OrderByDescending(column);
}

linqChain = linqChain.Where(...);

return linqChain.Execute();


The easy way to do this is to use Dynamic LINQ.


return (direction == "desc" ? persons.OrderByDescending(x => x.GetType().GetProperty(column).GetValue(x)).ToList() : persons.OrderBy(x => x.GetType().GetProperty(column).GetValue(x)).ToList());

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜