Group by days interval using Linq

Asked

Viewed 351 times

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 prices grouped for a range of days.

31 to 60;

61 to 90;

91 to 120;

121 to 150;

and greater than 150;

3 answers

4


You can use the group by to join everyone by the interval and then turn it 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 on Dotnetfiddle

  • 1

    Only missed for conditions is <= instead of <; Replaced Todictionary with Select.

1

Parameterize your upper bounds list 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.

0

Browser other questions tagged

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