I have to sort an array of strings. How can I do that, if:
- They must be placed in order of string length.
- If lengths are equal, the must be placed alphabetically.
Is there any simple to do that ?
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
Array.Sortand pass in anIComparer<string>or aComparison<string>... or you could use LINQ... have you tried anything yet? What happened?