Lexicographically sort C#

classical312 picture classical312 · Mar 1, 2016 · Viewed 12.3k times · Source

I have this code for sorting strings:

 class Program
{
    static void Main()
    {

        int x = Convert.ToInt32(Console.ReadLine());
        List<string> sampleList = new List<string>();

        for (int i=0; i<x; i++)
        {
            string word = Console.ReadLine();
            sampleList.Add(word);
        }


        foreach (string s in SortByLength(sampleList))
        {
            Console.Write(s);
        }
        Console.ReadLine();
    }

    static IEnumerable<string> SortByLength(IEnumerable<string> e)
    {
        // Use LINQ to sort the array received and return a copy.
        var sorted = from s in e
                     orderby s.Length descending
                     select s;
        return sorted;
    }
}

This code sorting strings by length, how can I do that by length and lexicographically ?

Example

//Input
4
abba
abacaba
bcd
er

//Output
abacabaabbabcder

In this case work fine, but when I have

//Input
5
abba
ebacaba
bcd
er
abacaba

//Output
ebacabaabacabaabbabcder

My first string is ebacaba which is wrong.

Answer

Quentin Roger picture Quentin Roger · Mar 1, 2016

You can use thenby :

static IEnumerable<string> SortByLength(IEnumerable<string> e)
{
    // Use LINQ to sort the array received and return a copy.
    var sorted = e.OrderByDescending(s=>s.Length).ThenBy(r=>r);                 
    return sorted;
}