使用属性变量对列表进行排序

Ale*_*rod 2 c# sorting reflection compare

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

List<Process> listProcess = new List<Process>();
Run Code Online (Sandbox Code Playgroud)

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

Arg*_*a C 5

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

var sortedList = list.OrderBy(o => o.GetType().GetProperty(propName).GetValue(o));
Run Code Online (Sandbox Code Playgroud)

在哪里

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