Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to group by and sum in linq

Posted on 2013-12-02
2
Medium Priority
?
803 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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

618 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