String Field List Sorting

Asked

Viewed 456 times

1

I have a List with attributes, of which I have the field of reviews, containing: Excellent, Good, Regular, Bad, and Bad. The information for this field I get from the consumption of a REST API using JSON.

Example:

IEnumerable<minhaEntidade> minhaLista = _respositorio.ConsumirAPI();

foreach (var item in minhaLista)
{
    Retorno.Add(new minhaNovaEntidade()
    {
            Nome = item.NomeCompleto,
            Endereco = item.EnderecoCompleto,
            Avaliacao = item.AvaliacaoDesempenho
    });
}

If I do:

return Retorno.OrderBy(x => x.Avaliacao);

I will have the list sorted by the performance evaluations in alphabetical order.

However, I need to sort the list by following the precedence criterion: Excellent, Good, Regular, Bad, and Bad.

That is, all Names and Addresses that were first evaluated as Excellent, then Good, then Regular, then Bad, then Bad. In this order.

I’ve tried to create a Type-Safe Enum Pattern to compare the obtained list with my Type-Safe Enumerator, example:

return Retorno.OrderBy(x => MeuEnumerador().CompareTo(x.Avaliacao));

or...

return Retorno.Sort((x,y) => x.Avaliacao.CompareTo(MeuEnumerador().ToString()))

But it didn’t work and/or make a mistake.

Questions:

Has anyone ever needed to do something similar to this problem of mine using C#?

Or even, have any hint of implementation for what I’m looking for?

Remembering that the information does not come from a database (which would be easy to solve), but from a JSON API, and the field is just a string.

  • What kind of Avaliacao?

  • @LINQ the Rating field is string type. And when I consume the API, it comes Excellent, or Good, or Regular, or Bad, or Bad.

  • IEnumerable<minhaEntidade> minhaLista in this variable already has the list of values, is why you need to order?

  • @Virgilionovic This is exactly the list I need to sort by the Evaluation field, which is string type, but not alphabetically. First sort all the cases that were evaluated by Excellent, then Good and so on.

  • I understand Alexandre Dórea.

2 answers

1

Hint to solve the problem. Create a weight field/attribute in your minhaNovaEntidade . When adding the new item to the return list put the weight value. After including all classified items, reorder the list based on weight. Example:

foreach (var item in minhaLista)
{
   xxx = new minhaNovaEntidade()
   {
        Nome = item.NomeCompleto,
        Endereco = item.EnderecoCompleto,
        Avaliacao = item.AvaliacaoDesempenho
   };

switch (item.AvaliacaoDesempenho)
        {
            case "Excelente":
                xxx.peso = 1;
                break;

            case "Bom";
                xxx.peso = 2;
                break;

            default:
                xxx.peso = 99;
                break;
        }

Retorno.Add(xxx);

}

return Retorno.OrderBy(x => x.peso);
  • I created a field as you suggested. But, I didn’t need to use the Switch. I took advantage of the concept I had already implemented of Type-Safe Enum Pattern and returned the value for this custom Enum. How to close and give validated points to what you suggested?

  • Click on the tag next to the answer For questions see https://answall.com/help/someone-answers

1


Create a enum for the classifications and order by it:

public enum Avaliacoes
{
    Excelente = 0,
    Bom = 1,
    Regular = 2,
    Ruim = 3,
    Pessimo = 4
}

I made an example code:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Lista Original:");

        List<Entidade> entidades = new List<Entidade>();
        entidades.Add(new Entidade(){ Id =1, Nome = "Teste 1", Avaliacao = Avaliacoes.Ruim });
        entidades.Add(new Entidade(){ Id =2, Nome = "Teste 2", Avaliacao = Avaliacoes.Pessimo });
        entidades.Add(new Entidade(){ Id =3, Nome = "Teste 3", Avaliacao = Avaliacoes.Regular });
        entidades.Add(new Entidade(){ Id =4, Nome = "Teste 4", Avaliacao = Avaliacoes.Bom });
        entidades.Add(new Entidade(){ Id =5, Nome = "Teste 5", Avaliacao = Avaliacoes.Ruim });
        entidades.Add(new Entidade(){ Id =6, Nome = "Teste 6", Avaliacao = Avaliacoes.Regular });
        entidades.Add(new Entidade(){ Id =7, Nome = "Teste 7", Avaliacao = Avaliacoes.Ruim });
        entidades.Add(new Entidade(){ Id =8, Nome = "Teste 8", Avaliacao = Avaliacoes.Bom });
        entidades.Add(new Entidade(){ Id =9, Nome = "Teste 9", Avaliacao = Avaliacoes.Ruim });
        entidades.Add(new Entidade(){ Id =10, Nome = "Teste 10", Avaliacao = Avaliacoes.Ruim });
        entidades.Add(new Entidade(){ Id =11, Nome = "Teste 11", Avaliacao = Avaliacoes.Bom });
        entidades.Add(new Entidade(){ Id =12, Nome = "Teste 12", Avaliacao = Avaliacoes.Excelente });
        entidades.Add(new Entidade(){ Id =13, Nome = "Teste 13", Avaliacao = Avaliacoes.Excelente });


        entidades.ForEach(x => Console.WriteLine(x.Nome + " / " + x.Avaliacao));

        entidades =  entidades.OrderBy(x => x.Avaliacao).ToList();


        Console.WriteLine("----------------------------------------------");
        Console.WriteLine("Lista Ordenada:");

        entidades.ForEach(x => Console.WriteLine(x.Nome + " / " + x.Avaliacao));


    }


    public class Entidade
    {
        public int Id {get;set;}
        public string Nome {get;set;}
        public Avaliacoes Avaliacao {get;set;}

    }

    public enum Avaliacoes
    {
        Excelente = 0,
        Bom = 1,
        Regular = 2,
        Ruim = 3,
        Pessimo = 4
    }
}

Upshot:

Lista Original:
Teste 1 / Ruim
Teste 2 / Pessimo
Teste 3 / Regular
Teste 4 / Bom
Teste 5 / Ruim
Teste 6 / Regular
Teste 7 / Ruim
Teste 8 / Bom
Teste 9 / Ruim
Teste 10 / Ruim
Teste 11 / Bom
Teste 12 / Excelente
Teste 13 / Excelente
----------------------------------------------
Lista Ordenada:
Teste 12 / Excelente
Teste 13 / Excelente
Teste 4 / Bom
Teste 8 / Bom
Teste 11 / Bom
Teste 3 / Regular
Teste 6 / Regular
Teste 1 / Ruim
Teste 5 / Ruim
Teste 7 / Ruim
Teste 9 / Ruim
Teste 10 / Ruim
Teste 2 / Pessimo

I put in the Dotnetfiddle

ps. You will need to convert the string that comes in json pro Enum, then: https://stackoverflow.com/a/16104/4713574

  • 1

    I will test convert to Enum. I hadn’t thought about it. Once I have the result I evaluate here.

  • 1

    I’m not sure, but it’s possible that in the json parse, it’s already converted to Enum automatically.

Browser other questions tagged

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