Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Nested string list in C#

Tags:

c#

sorting

What I want to achieve is a alphabetically sorted nested list.

E.g. my input:

fat, twat, gat    //Line 1
cat, hat, bat     // Line 2
twat, lack, rat   // Line 3

I want the output to be:

bat, cat, hat    // Line 2
fat, gat, twat   // Line 1
lack, rat, twat  // Line 3

As you can see, the list is sorted on the inside first, then also on the outside.

My implementation at the moment is using a nested list:

List<List<String>> testSort;

I have managed to sort the inside list using this method:

    public static List<List<String>> sortList(List<List<String>> input)
    {
        input.ForEach(delegate (List<string> o)
        {
            o.Sort();
        });

        return input;
    }

I'm unsure how to sort the list on the outside now. Help would be appreciated!

Thanks in advance!

like image 250
ForeverLearning Avatar asked Sep 13 '15 06:09

ForeverLearning


People also ask

Can we sort a nested list?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.

Can you sort a list in C#?

In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.


2 Answers

You can use OrderBy() to sort the outside list based on first element of each list, after each internal list is already sorted:

input.ForEach(t => t.Sort());
input = input.OrderBy(t => t.First()).ToList();

In response to M.kazem Akhgary comment below, I can only think of this solution if you want the sorting of the outer list not only based on the first element but the entire list. Maybe someone else has better solution.

input.ForEach(t => t.Sort());
input.Sort((e1, e2) => {
    for (int i = 0; i < e1.Count; i++)
    {
        if(e1[i] != e2[i])
        {
            return e1[i].CompareTo(e2[i]);
        }
    }

    return 0;
});
like image 96
Phuong Nguyen Avatar answered Oct 08 '22 06:10

Phuong Nguyen


Since the signature of sortList has a return type it is best not to modify the contents of the input list - that could just lead to side effects and buggy code.

Here's how I would tackle this:

public static List<List<String>> sortList(List<List<String>> input)
{
    return input
        .Select(x => x.OrderBy(y => y).ToList())
        .OrderBy(x => String.Join(", ", x))
        .ToList();
}

So, given this input:

var input = new List<List<string>>()
{
    new List<string>() { "fat", "twat", "gat", },
    new List<string>() { "cat", "hat", "bat", },
    new List<string>() { "twat", "lack", "rat", },
};

This would be the output:

output

like image 4
Enigmativity Avatar answered Oct 08 '22 06:10

Enigmativity