使用 属性 变量排序列表

sort list using property variable

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

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

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

你可以看看评论中提到的post。或者,您可以使用像这样的简单反射来实现

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