【问题标题】:sort list using property variable [duplicate]使用属性变量对列表进行排序[重复]
【发布时间】:2015-10-31 18:46:45
【问题描述】:

假设我有这个进程列表或任何其他对象

List<Process> listProcess = new List<Process>();

我可以使用这条线对其进行排序listProcess.OrderBy(p =&gt; p.Id); 但是,如果我只有在运行时获得的属性的字符串名称怎么办。我假设,我应该使用反射来获取属性对象。我可以使用 orderby 方法还是应该使用 Sort 然后传递自己的比较器?

【问题讨论】:

  • 您也可以使用带有名称的 OrderBy。您的问题到底是什么?
  • 使用反射也许.. 但是@DavidG 建议的副本很好地解决了您的问题。
  • @ArghyaC:嗯,你怎么能使用带有属性名称的 OrderBy 呢? (除了反射......)
  • @JonSkeet 哦哦!我的错!我认为 OP 有string 属性“名称”的值!是的,反思就是答案。 list.OrderBy(o =&gt; o.GetType().GetProperty(propName).GetValue(o))

标签: c# sorting reflection compare


【解决方案1】:

您可以查看评论中提到的帖子。或者,您可以使用像这样的简单反射来实现这一目标

var sortedList = list.OrderBy(o => o.GetType().GetProperty(propName).GetValue(o));

在哪里

List<object> list; //a list of any object(s)
string propName; //name of the property to be used in OrderBy

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2011-10-11
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多