Solved

How to group by and sum in linq

Posted on 2013-12-02
2
671 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
  • 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 500 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Vb.net dynamic formulas in runtime 11 61
Replace &lt; with < 14 56
Error on link 14 37
Javascript and Jquery not firing 9 39
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
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
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

911 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now