?
Solved

How to group by and sum in linq

Posted on 2013-12-02
2
Medium Priority
?
749 Views
Last Modified: 2016-02-10
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
0
Comment
Question by:countrymeister
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 11

Expert Comment

by:Angelp1ay
ID: 39691268
        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

0
 
LVL 11

Accepted Solution

by:
Angelp1ay earned 2000 total points
ID: 39691738
I figured I should put some example data in and explain better. I've added some data for Product Groups "G1" and "G2" spread over January and February and I've also added a second output which does exactly the same in Linq Method Syntax.

        public void MyFunction()
        {
            List<InputType> input = new List<InputType>();
            input.Add(new InputType() { Code = "C123", ProductGroup = "G1", Price = 1.00m, BusinessDate = new DateTime(1, 1, 1) });
            input.Add(new InputType() { Code = "C124", ProductGroup = "G1", Price = 2.00m, BusinessDate = new DateTime(1, 1, 15) });
            input.Add(new InputType() { Code = "C125", ProductGroup = "G1", Price = 3.00m, BusinessDate = new DateTime(1, 2, 4) });
            input.Add(new InputType() { Code = "C126", ProductGroup = "G1", Price = 4.00m, BusinessDate = new DateTime(1, 2, 26) });
            input.Add(new InputType() { Code = "C123", ProductGroup = "G2", Price = 1.00m, BusinessDate = new DateTime(1, 1, 1) });
            input.Add(new InputType() { Code = "C124", ProductGroup = "G2", Price = 1.00m, BusinessDate = new DateTime(1, 1, 15) });
            input.Add(new InputType() { Code = "C125", ProductGroup = "G2", Price = 1.00m, BusinessDate = new DateTime(1, 1, 4) });
            input.Add(new InputType() { Code = "C126", ProductGroup = "G2", Price = 1.00m, BusinessDate = new DateTime(1, 2, 26) });

            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),
                                             };

            IEnumerable<ResultType> output2 = input
                .GroupBy(x => new {x.ProductGroup,
                                   x.BusinessDate.Year,
                                   x.BusinessDate.Month})
                .Select(grp => new ResultType() {ProductGroup = grp.Key.ProductGroup, 
                                                 Month = new DateTime(grp.Key.Year, grp.Key.Month,1), 
                                                 Sum = grp.Sum(i => i.Price)});
        }

Open in new window

Both outputs do the same thing - the first is Linq Query Syntax, the second is Linq Method Syntax (but they both do exactly the same thing under the hood). You can use whichever you're more comfortable with or you find easier to read/maintain.

First I group using an anonymous type that contains all the attributes you want to group on (the product group, year and month).

Then I project the results into the desired target type, extracting the Product Group, Year and Month from the group, wrapping the Year and Month in a new DateTime, and finally by summing the price across the group.

As you can see in this debug screenshot, it works as expected (showing the second group which is Product Group G1 in Feb).
Stepping through showing Linq in action
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question