0

I have a table with data like

Year Month Date Sum1 
2019   01   01   11  
2019   02   03   12
2019   02   03   13  
2019   02   04   13  
2019   03   05   14  
2019   03   10   15  

How I can group that to get a result like

2019 +
     01 +
          01  11 
     02 + 
          03  25
          04  12
     03 +
          10  15
      04  13 

I've tried something like

IEnumerable<IGrouping<int, myList>> result= myList.GroupBy(x=>x.Year);

but I can't understand how I have to GroupBy that result. I want to group by year, then a month, then date and get total of Sum1 on date level How I can do that just with LINQ? I understand how I can do that within a lot of foreach, but maybe an elegant solution exists.

1 Answers1

1

I created a test object called myObject. I assume this is how you're storing your data from the table. If not, please provide your alternative and I will try to adjust.

Your LINQ could look like this: First it groups by all three properties (Year, Month, Date) all at once, then Select the Sum of each group.

var result = myList.GroupBy(o => new { o.Year, o.Month, o.Date })
                .Select(o => new myObject() {
                    Year = o.Key.Year,
                    Month = o.Key.Month,
                    Date = o.Key.Date,
                    Sum1 = o.Sum(x => x.Sum1)
                });
dvo
  • 2,113
  • 1
  • 8
  • 19