Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Natural numeric sort in C#

Tags:

c#

sorting

I have a problem when sorting a generic list in C#

I have a List<MyObjects> myList, and MyObject has a string property.

Now it looks like this when sorting descending

2.4.88

2.4.70

2.4.164 -> this is wrong

2.4.15

How do I sort my list?

I have tried:

myList.sort(delegate(MyObjects obj1, MyObjects obj2)
{
    return obj2.version.CompareTo(obj1.version);
});

Its not an option to use Linq (older framework)

UPDATE: My list can also contains N/A

like image 319
Millerbean Avatar asked Dec 27 '22 05:12

Millerbean


1 Answers

You cannot compare as strings, because obviously thats the proper string sorting. You need to parse to numbers or to an instance of the Version class:

myList.sort(delegate(MyObjects obj1, MyObjects obj2)
{
    return new Version(obj2.version).CompareTo(new Version(obj1.version));
});
like image 117
Paul Tyng Avatar answered Jan 16 '23 14:01

Paul Tyng