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!
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.
In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.
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;
});
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With