Order By with List

10

Is it 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();
    
asked by anonymous 04.05.2017 / 17:43

1 answer

10

Yes, it is possible. Using Linq's OrderBy

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

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

So, just reverse the expressions that your list will be sorted as you want

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

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

See an example ( you can see it working in .NET Fiddle ). It orders by placing first the one 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
}
    
04.05.2017 / 17:45