0

I'm fairly new in C# and just encountered a weird behavior.

This is a piece of script that should sort array of strings alphabetically (A-Z)

This is the array:

IFF-7/12
IFA-7/11
IFF-7/8
IFF-7/2
IFF-7/11
IFF-7/1
IF-7/1
IFF-7/6
IFF-7/9
IFF-7/13
IFF-7/14
IF-7/2

So I suppose the outcome should be:

IF-7/1
IF-7/2
IFA-7/11
IFF-7/1
IFF-7/2
IFF-7/6
IFF-7/8
IFF-7/9
IFF-7/11
IFF-7/12
IFF-7/13
IFF-7/14

Program script:

 for (int i = 0; i < faculty.GroupCount; i++)
        {
            for (int j = i + 1; j < faculty.GroupCount; j++)
            {
                if (faculty.Groups[j].Name.CompareTo(faculty.Groups[i].Name) < 0)
                {
                    temp = faculty.Groups[i];
                    faculty.Groups[i] = faculty.Groups[j];
                    faculty.Groups[j] = temp;
                }
            }
        }

But the actual outcome is

IF-7/1
IF-7/2
IFA-7/11
IFF-7/1
IFF-7/11
IFF-7/12
IFF-7/13
IFF-7/14
IFF-7/2
IFF-7/6
IFF-7/8
IFF-7/9

I see what it's doing but I have no idea why. Also I can't use any of the libraries or methods like .sort .

Thanks for any help.

Ned
  • 361
  • 3
  • 16
  • You should implement this using `IComparer` instead : https://msdn.microsoft.com/en-us/library/8ehhxeaf(v=vs.110).aspx – aybe Oct 09 '17 at 13:23
  • 5
    Because numbers sorted as string go 1,10,11,12,2,3,4,5,6,7,8,9 .. because all the ones come before 2.. – BugFinder Oct 09 '17 at 13:25
  • What you want is called a natural sort order, as opposed to alphabetical sort order (default implementation of `CompareTo`). There are multiple older question on that natural sorting: [1](https://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp), [2](https://stackoverflow.com/questions/3716831/sorting-liststring-in-c-sharp), [3](https://stackoverflow.com/questions/8568696/icomparer-for-natural-sorting). You might want to check them out and apply the code there to your particular problem. – default locale Oct 09 '17 at 13:29
  • Your supposed outcome is incorrect, because of the assumption that dash `-` sorts after letters, while in fact it sorts before letters, and even before digits (its hex code is 0x45, while the code of zero `'0'` is 0x48). – Sergey Kalinichenko Oct 09 '17 at 13:29

1 Answers1

3

1 comes before 2 in the order the same way that A comes before B, so 11 comes before 2.

You seem to want what is often called a "natural sort" which is like an alphabetical sort except that where two strings with the same beginning differ in numbers then the numerical value of the number as a whole (all of the run of digits) are compared. This isn't a collation provided by the .NET framework directly, but answers like this explain how to create an IComparer<string> that does a natural sort.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251