How to group records by month and year within a list of objects? ASP NET CORE

Asked

Viewed 167 times

0

I am trying to group the objects of a list by month or year, before returning the same.

I am trying this way and I did not succeed.

foreach (var item in passList)
{
   pass_obj = new Pass_returnDTO();
   pass_obj.pass_date_time = item.pass_date_time.Date;
   pass_obj.qty_pass = Convert.ToInt32(item.qty_daily_pass);
   listRegistro.Add(pass_obj);
}

if (grouper == "ano")
{
  objReturn.registros.GroupBy( d => d.pass_date_time.Year);
  listPassReturn.Add(objReturn);
}                  
else if (grouper == "mes")
{
  objReturn.registros.GroupBy(d => d.pass_date_time.Month);
  listPassReturn.Add(objReturn);
}
  • Already solved? In case you have not solved, you want to group by year and month and have the amount of records per grouping? It would be like: 2019-09 - quantity = 10, 2019-08 - quantity = 20...

  • Hello @Raquelpinheiro, already got it, thank you very much!

1 answer

1


//agrupando registros por ano
var lista = objReturn.register.GroupBy(d => d.pass_date_time.ToString("yyyy"))
           .Select(x => new { Year = x.Key, Sum = x.Sum(item => item.qty_pass) });

//agrupando registros por mês
var lista = objReturn.register.GroupBy(d => d.pass_date_time.ToString("yyyy/MM"))
           .Select(x => new { Month = x.Key, Sum = x.Sum(item => item.qty_pass) });   

Browser other questions tagged

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