【问题标题】:Sorting list using reflection使用反射排序列表
【发布时间】:2011-08-04 13:42:18
【问题描述】:

我有一张表,我想为每一列做排序功能。

排序有两个方向asc和desc。

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

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

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

    }

【问题讨论】:

  • 为什么是javascript 标签?
  • web-development 也不是必需的,因为尽管您可能正在做 Web 开发,但回答问题并不需要这些知识,而且问题与它无关。跨度>
  • 对不起。我只是在写js网格,忘记了这个问题只是关于排序c#列表。
  • @Henk Holterman 因为我们用来排序的 person 字段作为字符串(列)传递给排序函数。

标签: c#


【解决方案1】:

试试这样的

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

【讨论】:

  • 我喜欢这个,它对我有用,但我意识到我需要按多个字段排序,而不仅仅是一个:(
【解决方案2】:

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

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

2) 您可以使用表达式对象将 LINQ 表达式连接在一起。

Expression linqChain = persons;

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

linqChain = linqChain.Where(...);

return linqChain.Execute();

【讨论】:

    【解决方案3】:

    执行此操作的简单方法是使用Dynamic LINQ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多