You need to sort the strings of a two-dimensional list using StringComparer.Ordinal - C #

List<List<string>> tbl = new List<List<string>>(); 

In case of equality of the elements of the rows in the 1st column, the sorting by the 2nd one, etc.

Example:

At the entrance:

 tbl ={ { fedya, developer, html}, { Ivan, manager, html}, { Ivan, manager ,exe} { fedya, manager ,html}, } 

At the exit:

 tbl ={ { Ivan, manager ,exe} { Ivan, manager ,html}, } { fedya, developer, html}, { fedya, manager, html}, 
  • What is a two-dimensional List? - Andrei NOP
  • List <List <string >> tbl = new List <List <string >> (); - Sergey Bekmambetov
  • You were also given an example code with OrderBy . Simply apply ThenBy for the second, third, and so on columns. - Alexander Petrov
  • Write how it will be with the use of StringComparer.Ordinal, sorting is very necessary, first large and then small letters - Sergey Bekmambetov

2 answers 2

We make OrderBy on 0th elements and, then, ThenBy on the rest:

 var list = new List<List<string>> { new List<string> { "fedya", "developer", "html"}, new List<string> { "Ivan", "manager", "html"}, new List<string> { "Ivan", "manager", "exe"}, new List<string> { "fedya", "manager", "html"} }; var result = list.OrderBy(x => x[0], StringComparer.Ordinal); for (int i = 1; i < list[0].Count; ++i) { // Очень важно скопировать в переменную с ограниченной областью видимости, // для подробностей читайте про замыкания в C# int index = i; result = result.ThenBy(x => x[index], StringComparer.Ordinal); } Console.WriteLine(string.Join("\n", result.Select(x => string.Join(", ", x)))); Console.ReadLine(); 

Conclusion:

 Ivan, manager, exe Ivan, manager, html fedya, developer, html fedya, manager, html 

All nested lists must have the same number of items.

  • How to add StringComparer.Ordinal? - Sergey Bekmambetov
  • @SergeyBekmambetov, specify the second parameter in OrderBy and ThenBy - Andrey NOP
  • Please, make your conclusion not the same, look in the example - Sergey Bekmambetov
  • one
    @ SergeyBekmambetov, well, naturally, if you change conditions on the fly - Andrey NOP
  • Sorry, it happened, according to the task you need - Sergey Bekmambetov

That's how it all works.

 table = table.OrderBy(x => x[0], StringComparer.Ordinal).ThenBy(x => x[1], StringComparer.Ordinal).ThenBy(x => x[2], StringComparer.Ordinal).ToList(); 
  • one
    I have the same answer, just for a predetermined number of elements. If you end up with a List, you can call it after the cycle: table = result.ToList() - Andrey NOP