[c#] Sorting string array in C#

Maybe it sounds weird, but after a long time programming, I just got on array sorting. Everything was as I expected, until I tried to sort an array of strings containing two identical strings inside. Let's see:

Suppose having the following:

string[] testArray = new string[]
    {
        "aa",
        "ab",
        "ac",
        "ad",
        "ab",
        "af"
    };

Array.Sort(testArray, StringComparer.InvariantCulture);

In this situation I get an array plain of null values. I got that this behavior is because the values inside array are not distinct values. Is there a better explanation for this? How do I sort a non-distinct array?

This question is related to c# arrays sorting

The answer is


Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here


If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:

var arr = arr.OrderBy(x=>x).ToArray();