Order By with List<>

Asked

Viewed 5,341 times

10

It is possible to make a OrderBy in a List<> setting the value for comparison?

Example:

mRel.OrderBy(s => s.Status == EnumModel.StatusGeral.Novo).ToList()

My Code:

List<MotivosModel.MotivosRel> mRel = CarregarMotivosRelacionados(null);

mRel = mRel.OrderBy(s => s.Status == EnumModel.StatusGeral.Novo)
           .ThenBy(s => s.Status == EnumModel.StatusGeral.Falha).ToList();

1 answer

10


Yes, it is possible. Using the method OrderBy linq.

You just need to note that the ordination s.Status == EnumModel.StatusGeral.Novo will place the elements that meet this condition pro final.

This is because the ordering is done based on the result of the expression, i.e., true (1) and false (0). Soon, anything that does not meet the condition will be put forward (this, if using ascending ordering, obviously).

Then, just invert the expressions that your list will be ordered as you want

mRel = mRel.OrderBy(s => s.Status != EnumModel.StatusGeral.Novo)
            .ThenBy(s => s.Status != EnumModel.StatusGeral.Falha)
            .ToList();

Obviously it is also possible only by changing the methods by OrderByDescending and ThenByDescending.

Take an example (you can see it working on . NET Fiddle). He orders putting first who has the status as Novo and then as Falha.

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var lista = new[] { new Coisa { Nome = "Novo Teste", Status = StatusGeral.Novo}, 
                            new Coisa { Nome = "Falha Teste", Status = StatusGeral.Falha}, 
                            new Coisa { Nome = "Novo Teste 2", Status = StatusGeral.Novo},
                            new Coisa { Nome = "Outro Teste", Status = StatusGeral.Outro} };

        lista = lista.OrderBy(s => s.Status != StatusGeral.Novo)
                     .ThenBy(s => s.Status != StatusGeral.Falha)
                     .ToArray();

        foreach(var p in lista)
        {
            Console.WriteLine(p.Nome);
        }           
    }
}

public class Coisa
{
    public String Nome { get; set; }
    public StatusGeral Status { get; set; }
}

public enum StatusGeral
{
    Novo,
    Falha,
    Outro
}
  • That way you can get to 100k in no time :)

  • What do you mean? @Ismael

  • For the great quick responses!

  • Ah, thank you =) @Ismael

  • Perfect friend, thank you so much for the help. the ordering I did using the Orderbydescending. mRel = mRel.Orderbydescending(s => s.Status == Enummodel.StatusGeral.New). Thenbydescending(s => s.Status == Enummodel.StatusGeral.Fault). Tolist();

  • Exactly. The end result is the same. Good help. = D

Show 1 more comment

Browser other questions tagged

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