How to sort a list of objects through a custom criterion (no order by)?

Asked

Viewed 30 times

0

I ask for your help in solving a problem that’s been bothering me. I have a list of scales and would like to sort it through the Status(which in turn is a property of Horarioescala entity, but the criterion is not alphabetical order, would thus be, the scales with status "Waiting Attendance" would be at the top of the listing, followed by the status "In attendance", and finally, the scales with "Attendance closed", I already thought about the possibility of transforming this Status from string to Enum to be able to use the Orderby function, but there are already many records in the database and then it wouldn’t work, anyway, I need help with logic to solve this problem, follows a part of the code

public async Task<IEnumerable<EscalaViewModel>> ObterPorContratadaId(string contratadaId)
    {
        var escalas = await _escalaRepository.ObterPorContratadaId(contratadaId);
        var escalaView = new List<EscalaViewModel>();
        var cultureInfo = new CultureInfo("pt-BR");

        if (escalas != null)
        {
            foreach (var escala in escalas)
            {
                var dataEscala = new List<DataEscalaViewModel>();
                foreach (var itemData in escala.DataEscalas.OrderBy(x => Convert.ToDateTime(x.DataEntrada, cultureInfo)))
                {
                    if (itemData.DataEntrada == DateTime.Now.ToString("dd/MM/yyyy"))
                    {
                        var horarioEscala = new List<HorarioEscalaViewModel>();
                        foreach (var horario in itemData.Horarios)
                        {
                            var entrada = new EntradaViewModel();
                            if (horario.Entrada != null)
                            {
                                entrada = new EntradaViewModel
                                {
                                    DataCheckIn = horario.Entrada.DataCheckIn,
                                    HoraCheckIn = horario.Entrada.HoraCheckIn,
                                    LatitudeCheckIn = horario.Entrada.LatitudeCheckIn,
                                    LongitudeCheckIn = horario.Entrada.LongitudeCheckIn
                                };
                            }

                            var saida = new SaidaViewModel();
                            if (horario.Saida != null)
                            {
                                saida = new SaidaViewModel
                                {
                                    DataCheckOut = horario.Saida.DataCheckOut,
                                    HoraCheckOut = horario.Saida.HoraCheckOut,
                                    LatitudeCheckOut = horario.Saida.LatitudeCheckOut,
                                    LongitudeCheckOut = horario.Saida.LongitudeCheckOut
                                };
                            }
                            horarioEscala.Add(new HorarioEscalaViewModel
                            {
                                Id = horario.Id,
                                TipoEscala = horario.TipoEscala,
                                MotivoDaEscala = horario.MotivoDaEscala,
                                HorarioInicio = horario.HorarioInicio,
                                HorarioFim = horario.HorarioFim,
                                Entrada = entrada,
                                Saida = saida,
                                TipoProfissional = horario.TipoProfissional,
                                ProfissionalId = horario.ProfissionalId,
                                ProfissionalUsuarioId = horario.ProfissionalUsuarioId,
                                PrestadorServicoId = horario.PrestadorServicoId,
                                NomePrestadorServico = horario.NomePrestadorServico,
                                NomeProfissional = horario.NomeProfissional,
                                AtividadeContratada = horario.AtividadeContratada,
                                Funcao = horario.Funcao,
                                Local = horario.Local,
                                Valor = horario.Valor,
                                Status = horario.Status,
                                CargoProfissional = horario.CargoProfissional,
                                RelatorioGerado = horario.RelatorioGerado
                            });


                            dataEscala.Add(new DataEscalaViewModel
                            {
                                Id = itemData.Id,
                                DataEntrada = itemData.DataEntrada,
                                DataSaida = itemData.DataSaida,
                                Horarios = horarioEscala
                            });

                        }
                    }
                    
                }
                if (dataEscala.Count() > 0)
                    escalaView.Add(new EscalaViewModel
                    {
                        Id = escala.Id,
                        HomeCareId = escala.HomeCareId,
                        PacienteId = escala.PacienteId,
                        DataEscalas = dataEscala

                    });

            }
        }

        return escalaView;
    }
  • The answer came true?

  • Hello, thank you so much for your help because it served as a basis to solve, I was searching and I realized that the solution would come from the front, I used the function compare and assign sequential values (as in the example you gave) for each status, with that I finally managed to order, muuuuuuito thanks even, improved my way of thinking

  • So if it’s useful, tick as the answer to your question

1 answer

1

I would make a junction between the three types with the method Concat of filtering the parameters in sequence, example:

using System;
using System.Collections.Generic;
using System.Linq;
class Item {
    public int Id {get;set;}
    public string Status {get;set;}
}
class Items: List<Item> 
{
    public Items() 
    {
        Add(new Item { Id = 1, Status = "Aguardando Atendimento" });
        Add(new Item { Id = 2, Status = "Atendimento encerrado" });
        Add(new Item { Id = 3, Status = "Em atendimento" });
        Add(new Item { Id = 4, Status = "Atendimento encerrado" });
        Add(new Item { Id = 5, Status = "Aguardando Atendimento" });
    }
}
public class Program
{
    public static void Main()
    {   
        //"Aguardando Atendimento"
        //"Em atendimento"
        //"Atendimento encerrado"
        Items items = new Items();
        var ordenado = items.Where(x => x.Status == "Aguardando Atendimento")
                .Concat(items.Where(x => x.Status == "Em atendimento"))
                .Concat(items.Where(x => x.Status == "Atendimento encerrado"));
                
        foreach(var c in ordenado)
        {
            Console.WriteLine("{0} - {1}", c.Id, c.Status);
        }
    }
}

Online Example


Another way is to create a class that will compare these values with the implementation of interface Icomparer<>, and thus use the Orderby with the second parameter: OrderBy(x => x.Status, new StatusComparer()), complete example:

using System;
using System.Collections.Generic;
using System.Linq;
class Item {
    public int Id {get;set;}
    public string Status {get;set;}
}
class Items: List<Item> 
{
    public Items() 
    {
        Add(new Item { Id = 1, Status = "Aguardando Atendimento" });
        Add(new Item { Id = 2, Status = "Atendimento encerrado" });
        Add(new Item { Id = 3, Status = "Em atendimento" });
        Add(new Item { Id = 4, Status = "Atendimento encerrado" });
        Add(new Item { Id = 5, Status = "Aguardando Atendimento" });
    }
}
class StatusComparer : IComparer<string>
{
    private Dictionary<string, string> Filters = 
        new Dictionary<string, string>(3);
    public StatusComparer()
    {
        Filters.Add("Aguardando Atendimento", "a");
        Filters.Add("Em atendimento", "b");
        Filters.Add("Atendimento encerrado", "c");
    }
    public int Compare(string x, string y)
    {
        string aX = Filters[x];
        string yX = Filters[y];
        return aX.CompareTo(yX);
    }
}
public class Program
{
    public static void Main()
    {   
        //"Aguardando Atendimento"
        //"Em atendimento"
        //"Atendimento encerrado"
        Items items = new Items();
        var ordenado = items.OrderBy(x => x.Status, new StatusComparer());
        foreach(var c in ordenado)
        {
            Console.WriteLine("{0} - {1}", c.Id, c.Status);
        }
    }
}

Online Example

Browser other questions tagged

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