Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a generic sort by string field method

Tags:

c#

sorting

c#-4.0

I've got a situation here and I'm not sure what the best way of proceeding is...

My front end code (ASP.NET) constantly gets lists of business objects for populating UI components. Recently, I implemented a Natural Sort that I want to use for all types of these lists. (currently it just sorts Lists of Strings) Depending on the type of business object, I need to sort on a different field name. The field always contains a string. I know the field name at compile time. The business objects do not have a common parent aside from Object.

I'd like to have one method which can do this for an Enumerable of any type. I cannot change the code for the underlying business objects. How would you go about this?

like image 284
Erix Avatar asked Apr 27 '26 17:04

Erix


1 Answers

Something like Linq's orderby?

You'd have to implement your natural sort in an IComparer, but then you'd just use:

Items.OrderBy(i => i.SomeStringField, NaturalSorter);
like image 168
Massif Avatar answered Apr 29 '26 07:04

Massif