Avatar of countrymeister
countrymeister
 asked on

How to group by and sum in linq

I have a list <T>

within which i have four fields

Code   - string
ProductGroup string
Price - decimal
BusinessDate - datetime


I need to Group by  ProductGroup, and BusinessDate ( just the month and year part)
Meaning all dates in a month are grouped, and I need to sum the Price to give me a new list

T1

with

ProductGroup
BusDate ( this would hold just 01/MM/YYYY)
Price (sum of all prices in that month
C#.NET ProgrammingLINQ Query

Avatar of undefined
Last Comment
Angelp1ay

8/22/2022 - Mon
Angelp1ay

        private class InputType
        {
            public String Code;
            public String ProductGroup;
            public Decimal Price;
            public DateTime BusinessDate;
        }

        private class ResultType
        {
            public String ProductGroup;
            public Decimal Sum;
            public DateTime Month;
        }

        public void MyFunction()
        {

            List<InputType> input = new List<InputType>();

            IEnumerable<ResultType> output = from c in input
                                             group c by new
                                             {
                                                 c.ProductGroup,
                                                 c.BusinessDate.Year,
                                                 c.BusinessDate.Month,
                                             } into grp
                                             select new ResultType()
                                             {
                                                 ProductGroup = grp.Key.ProductGroup,
                                                 Month = new DateTime(grp.Key.Year, grp.Key.Month, 1),
                                                 Sum = grp.Sum(s => s.Price),
                                             };
        }

Open in new window

ASKER CERTIFIED SOLUTION
Angelp1ay

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61