How to group items in a list with a proper condition?

Asked

Viewed 801 times

4

I have a list with a property called tamanho which may contain two values: "M" or "I".

I need this list to be random, but with a grouping condition.

"M" would be half page and "I" full. That is, I need to always have 1 whole and then 2 socks. Never 1 whole, 1 half and then 1 whole again.

I will use this to generate a PDF, as soon as I am sweeping the list it will insert 2 socks on the same page, or 1 whole, and never 1 half and more a whole then as the whole will not fit on the same page of the sock and will get a space.

My question is about the logic I need to apply to the list to get this result. I have no idea yet and need help.

inserir a descrição da imagem aqui

The code is just a C list#.

List<Questao> questao = new List<Questao>();
// questao.Questao.TipoTamanhoQuestao acessa o valor "M" ou "I"
  • 1

    Could present the code implemented so far?

  • The code is just a C list. I saw no need to put.

  • 1

    A small observation: the variable should be called questoes and not questao, since it’s a list.

1 answer

3


Use this extension. It goes through the list and:

  • if you find a "I" size question, return it immediately
  • if you find a "M" size question, store it in a buffer until you find a matching pair. When the pair is found, both will be returned.

If there is any "M" question without pair, it will be returned at the end.

public static class QuestoesExt
{
    public static IEnumerable<Questao> Grouped(this IEnumerable<Questao> questoes)
    {
        Questao buffer = null;

        foreach(var q in questoes)
        {
            if(q.TipoTamanhoQuestao == "M")
            {
                if(buffer == null)
                {
                    //Se a questao for de meia pagina, guardar num buffer ate que outra questao M apareça
                    buffer = q;
                }
                else
                {
                    //Quando um par de questoes M forem encontradas, retornar ambas
                    yield return buffer;
                    yield return q;
                    buffer = null;
                }
            }
            else yield return q;
        }

        //Se for encontrada alguma questao M sem par, retorná-la no final
        if(buffer != null)
            yield return buffer;
    }
}

Utilizing:

var grouped = questoes.Grouped();

Fiddle: https://dotnetfiddle.net/Nol3mp

Browser other questions tagged

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