Order by com List<>

Is it possible to effect a OrderBy on a List<> by 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();
Author: LINQ, 2017-05-04

1 answers

Yes, it is possible. Using the method OrderBy from Linq.

You just need to pay attention that the ordering s.Status == EnumModel.StatusGeral.Novo will put the elements that meet this condition Pro final .

This is because the sorting 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 in front (this, if you are using Ascending Sort, Of course).

So just invert 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();

Is obviously also possible only by swapping the methods for OrderByDescending and ThenByDescending.

See an example ( you can see it working in .NET Fiddle ). It orders by placing 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
}
 10
Author: LINQ, 2017-05-05 20:01:33