Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of different objects by a common property

I have a List<object> that contains instances of three types GuestbookEntry, Comment and SectionEntry. Those three classes have a common CreateDate property.

Is there any way that I am able to sort this list on a given property (which I know all the objects have) without knowing the type of the object?

like image 786
bomortensen Avatar asked Dec 05 '25 05:12

bomortensen


1 Answers

If you can't make those two classes derive from a common Interface\ Base Class Which is the best Object Oriented solution.
You can cast the the list items to dynamic.

List<object> list = GetListFromSomeWhere();
var dynamicList = list.Cast<dynamic>();

Then sort the dynamic list without compilation errors:

dynamicList.OrderBy(x => x.CreateDate); 
like image 97
gdoron is supporting Monica Avatar answered Dec 07 '25 18:12

gdoron is supporting Monica



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!