Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort list using property variable [duplicate]

Suppose I have this list of process or any other object

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

I can sort it using this line listProcess.OrderBy(p => p.Id); But what if I have only string name of property obtained in runtime. I assume, I should use reflection to get the property object. Can I use orderby method or I should use Sort and then pass own comparer?

like image 494
Alex Akselrod Avatar asked Jul 27 '26 18:07

Alex Akselrod


1 Answers

You can have a look at the post referred in the comment. Or, you can achieve that using simple reflection like this

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

Where

List<object> list; //a list of any object(s)
string propName; //name of the property to be used in OrderBy
like image 58
Arghya C Avatar answered Jul 29 '26 07:07

Arghya C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!