Sorting string array in C# [closed]

2020-02-25 04:25发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 7 years ago.

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?

回答1:

This code snippet is working properly



回答2:

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();


回答3:

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: