How to sort list with complex object by one of its properties?

Asked

Viewed 14,262 times

16

I have a list of objects and I want to sort the list by one of the properties (Desc type string), how do I do this?

public class Foo
{
    public string Desc { get; set; }

    // Várias outras propriedades
}

public class Program
{
    static void Main()
    {
        List<Foo> objetos = Program.PreencheObjetos();

        objetos.Sort();
    }

    public static List<Foo> PreencheObjetos()
    {
        // Retorna uma lista preenchida.
    }
}

I couldn’t use Sort to do that.

5 answers

12

You can use Lynne for that:

objetos = objetos.OrderBy(o => o.Desc).ToList();

or passing a function on . Sort()

objetos.Sort((o1,o2) => o1.Desc.CompareTo(o2.Desc));

9


You can work with sorting using the method List<T>.Sort(IComparer <T>) (documentation on MSDN) implementing the interface IComparer (documentation on MSDN) in the classes of objects you want to sort. See how:

In the class of objects

public class ComparadorDoMeuObjeto: IComparer<MeuObjeto>  {
    int IComparer.Compare( MeuObjeto x, MeuObjeto y )  {
        if(x == null)
            return -1;
        if(y == null)
            return 1;

        return x.PropriedadeInterna - y.PropriedadeInterna ;
    }
}

See how to implement

+-------------------+--------------------+ 
| Valor             | Significado        | 
+-------------------+--------------------+ 
| menor que zero    | x é menor do que y | 
| zero              | x é igual a y      | 
| maior do que zero | x é maior do que y | 
+-------------------+--------------------+ 

How to make the ordination

 List<MeuObjeto> objs= new List<MeuObjeto>();
 objs.Add(new MeuObjeto(1));
 objs.Add(new MeuObjeto(2));
 objs.Add(new MeuObjeto(3));
 objs.Add(new MeuObjeto(4));

 ComparadorDoMeuObjeto comparador = new ComparadorDoMeuObjeto();

 // Com objeto IComparer
 objs.Sort(comparador);
 // Com Lambda para fazer a mesma coisa (parâmetros do IComparer)
 objs.Sort((x, y) => x.PropriedadeInterna  - y.PropriedadeInterna);
  • How would it be to sort a complex object, such as Category?

  • Alphabetically? Numerically speaking? Please place an answer here with your attempt to use this model on your object and a simple object model for me to see. It can be a link to a github gist as well...

3

Try to use Linq:

    var objetosEmOrdem = (from o in objetos
                          orderby o.Desc
                          select s);

2

2

See if this is what you want

public class Foo
{
    public int Codigo { get; set; }
    public string Nome { get; set; }
    public string Sobrenome { get; set; }

    // Várias outras propriedades
}

public class Program
{
    static void Main()
    {
        List<Foo> objetos = Program.PreencheObjetos();

        objetos.OrderBy(a => a.Nome);
        objetos.OrderBy(a => a.Codigo);
        objetos.OrderBy(a => a.Sobrenome);

        objetos.OrderByDescending(a => a.Nome);
        objetos.OrderByDescending(a => a.Codigo);
        objetos.OrderByDescending(a => a.Sobrenome);
    }

    public static List<Foo> PreencheObjetos()
    {
        List<Foo> list = new List<Foo>();
        for (int i = 0; i < 10; i++)
        {
            list.Add(new Foo() { Codigo = i, Nome = "Nome " + i, Sobrenome = "Sobrenome " + i });

        }

        return list;

    }
}
  • The calls to Orderby and Orderbydescending do not order the list, they return an ordered result. You should take the value of the sorts in another variable, not just call it (as with the Sort method of List<T>).

Browser other questions tagged

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