使用反射排序列表 [英] Sorting list using reflection

查看:44
本文介绍了使用反射排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,我想对每一列进行排序.

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

排序有两个方向,升序和降序.

Sorting has two direction asc and desc.

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

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)另外,我想做一些我可以称之为linq运算符链的事情:

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 => GetProperyByName(x, column))
         }

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

         return linqChain.Execute();

    }

推荐答案

1)如果要使用列的字符串名称进行排序,请使用

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)您可以使用表达式对象将LINQ表达式连接在一起.

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

这篇关于使用反射排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆