Group by interval of days using Linq

4

How can I use interval grouping with Linq?

var dados = new[] {
    new { Id = 0, dias=100, preco= 25,  Nome="etc"},
    new { Id = 1, dias=40,  preco= 50,  Nome="etc1"},
    new { Id = 2, dias=50,  preco= 55,  Nome="etc2"},
    new { Id = 3, dias=80,  preco= 70,  Nome="etc3"},
    new { Id = 4, dias=150, preco= 90,  Nome="etc4"},
    new { Id = 5, dias=420, preco= 100, Nome="etc5"},
    new { Id = 6, dias=122, preco= 500, Nome="etc6"},
};

Using Linq how can I return a list with the sum of the grouping prices by a range of days.

  

31 to 60;

     

61 to 90;

     

91 to 120;

     

121 to 150;

     

and greater than 150;

    
asked by anonymous 08.06.2017 / 21:57

3 answers

4

You can use group by to join all by the range and then transform into a dictionary by taking the group key as the Key and the sum of the price as Value

var dic=dados.OrderBy(x=>x.dias).GroupBy(x =>
        {
            if (x.dias > 30 && x.dias < 60)
                return "31 a 60";
            if (x.dias > 60 && x.dias < 90)
                return "61 a 90";
            if (x.dias > 90 && x.dias < 120)
                return "91 a 120";
            if(x.dias > 120 && x.dias < 150)
                return "121 a 150";

            return "maior que 150";
        }).ToDictionary(k => k.Key, v => v.Sum(y => y.preco));

See working at DotNetFiddle

    
09.06.2017 / 00:45
1

Parametrize your list of upper boundaries by using it in GroupBy .

var limites = new[] {60, 90, 120, 150, 420};

var grupos = dados.GroupBy(dado => limites.First(limite => limite >= dado.dias))
                  .Select(grupo => new { Soma = grupo.Select(g => g.preco).Sum() });

Example working on DotNetFiddle .

    
09.06.2017 / 02:29
0

I used the answer from James S as a base and stayed as I wish, see answer on the link DotNetFiddle Answer

    
09.06.2017 / 15:36