-3

I have to sort an array of strings. How can I do that, if:

  1. They must be placed in order of string length.
  2. If lengths are equal, the must be placed alphabetically.

Is there any simple to do that ?

5
  • 1
    What code do you have so far? Commented Mar 17, 2016 at 17:21
  • 3
    Well you can call Array.Sort and pass in an IComparer<string> or a Comparison<string>... or you could use LINQ... have you tried anything yet? What happened? Commented Mar 17, 2016 at 17:22
  • take a look at this dotnetperls.com/sort Commented Mar 17, 2016 at 17:22
  • Thanks for the answers, but it need the solution without using LINQ, that's why I created question. I should have mentioned that before. Commented Mar 17, 2016 at 17:30
  • @Imugi, so you should write your own way of sorting? Commented Mar 17, 2016 at 17:35

2 Answers 2

1

Here's the traditional way in C# ...

static void Main(string[] args)
{
    List<string> list = new List<string>();
    list.Add("1991728819928891");
    list.Add("0991728819928891");
    list.Add("3991728819928891");
    list.Add("2991728819928891");
    list.Add("Hello");
    list.Add("World");
    list.Add("StackOverflow");
    list.Sort(
        delegate (string a, string b) {
            int result = a.Length.CompareTo(b.Length);
            if (result == 0 )
                result = a.CompareTo(b);
            return result;
        }
    );

    Console.WriteLine(string.Join("\n", list.ToArray()));
}

Sample Output:

Hello
World
StackOverflow
0991728819928891
1991728819928891
2991728819928891
3991728819928891
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with LINQ in the following way:

string[] arr = new[] { "aa", "b", "a" , "c",  "ac" };
var res = arr.OrderBy(x => x.Length).ThenBy(x => x).ToArray();

Another way is to use Array.Sort with custom IComparer implementation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.