How to sort a list of objects by DUAS properties

6

In this topic: How to sort list with complex object by one of its properties? is explained how to sort by a property, but how to sort by two?

Considering the following product class:

+-------------------+--------------------+ 
| Produto                                | 
+-------------------+--------------------+ 
| Código            | int                | 
| Nome              | string             | 
| Preço             | double             | 
| Categoria         | Categoria          | 
+-------------------+--------------------+ 

And the category class

+-------------------+--------------------+ 
| Categoria                              | 
+-------------------+--------------------+ 
| Código            | int                | 
| Nome              | string             | 
+-------------------+--------------------+ 

And imagining a list of products.

How can I sort the list alphabetically by the name of its category, followed by alphabetical order of the name itself? Is it possible to use IComparer ?

    
asked by anonymous 01.04.2014 / 20:57

1 answer

7

Do with Linq, first make sure you are referencing:

using System.Linq;

Then use this:

var ordenada = lista.OrderBy(m => m.Categoria.Nome).ThenBy(m => m.Nome);

Use the ordenada return list to go through. So:

foreach (var item in ordenada)
{
    Console.WriteLine(item.Nome + " - " + item.Categoria.Nome);
}

Using the query syntax in this way is equivalent to the previous one:

var ordenada = from m in lista
               orderby m.Categoria.Nome, m.Nome
               select m;

OrderBy returns a list of type IOrderedEnumerable<T> so it is only possible to use ThenBy after OrderBy . If it were necessary to add a third property it would come with another ThenBy and so on.

If you just wanted to change the original list without having a new copy ordered, you could do this by calling the ToList() method in this way:

lista = lista.OrderBy(m => m.Categoria.Nome).ThenBy(m => m.Nome).ToList();

See that you could also call OrderBy twice as follows:

var ordenada = lista.OrderBy(m => m.Nome).OrderBy(m => m.Categoria.Nome);

It would be necessary to invert the sequence, since the entire list would be sorted twice (which should be less performative). However, in addition to not being very semantic, it is also not the form of use for which OrderBy was designed.

    
01.04.2014 / 21:03