How to group items in a list with a condition?

4

I have a list with a property called tamanho which can 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" would be whole. That is, I need to always have 1 integer 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 it is sweeping the list it will insert 2 socks on the same page, or 1 integer, and never 1 half and one integer then, since the whole one will not fit on the same page half and will stay a space.

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

ThecodeisjustaC#list.

List<Questao>questao=newList<Questao>();//questao.Questao.TipoTamanhoQuestaoacessaovalor"M" ou "I"
    
asked by anonymous 28.07.2015 / 19:20

1 answer

3

Use this extension. It traverses the list and:

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

If there is an unmatched "M" question, 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;
    }
}

Usage:

var grouped = questoes.Grouped();

Fiddle: link

    
28.07.2015 / 21:13