How to sort a list 1 to N with Expression lambda

Asked

Viewed 52 times

0

I need to sort out a list and I don’t know where to start.

I tried to apply the code below based on some posts, for example: https://stackoverflow.com/questions/298725/multiple-order-by-in-linq , but I really don’t know how to do:

var ret = objCliente.ListaDeClientes();
var retCli = ret.OrderBy(x => x.ID_PAI).ThenBy(x => x.ID_PAI_FILHO);

Can anyone direct me ? or shows an example of how to do ?
The list on the left is disorganized and I need to leave it as the list on the right:

inserir a descrição da imagem aqui

  • No matter the lists, present the structure of the two classes. It seems you want an orderly parent list, with your children ordered... It seems to me that these objects should be nesting and not at the same level of hierarchy

  • @Leandro Angelo the class contains other attributes that I did not present here because it is irrelevant, this list returns from a legacy as I posted, the problem is that I need to sort this list the way I put in the post.

  • It does not explain the ordering, what is the logic of its ordering

1 answer

0

I understand your need. But do you need this to be done specifically in a lambda expression? Can’t you use LINQ? If you can, here’s an example:

List<Objeto> retAux = new List<Objeto>();
List<Objeto> ret = objCliente.ListaDeClientes();

// Recupera os objetos pai
var listaRetPais = ret.Where(x => x.ID_PAI > 0 && x.ID_PAI_FILHO == 0).ToList();

// Percorre os objetos pai
foreach (var retPai in listaRetPais)
{
    // Popula o pai em uma lista auxiliar
    retAux.Add(new Objeto()
    {
        ID_PAI = retPai.ID_PAI,
        FILHO = retPai.FILHO,
        ID_PAI_FILHO = retPai.ID_PAI_FILHO
    });

    // Percorre os objetos filhos do objeto pai atual
    foreach (var retFilho in ret.Where(x => x.ID_PAI == retPai.ID_PAI).ToList())
    {
        // Popula os filhos
        retAux.Add(new Objeto()
        {
            ID_PAI = retFilho.ID_PAI,
            FILHO = retFilho.FILHO,
            ID_PAI_FILHO = retFilho.ID_PAI_FILHO
        });
    }
}

At the end of the process you will have your list sorted in the way you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.