Solved

LINQ - Groupby datatable & sum C#

Posted on 2011-02-13
6
2,776 Views
Last Modified: 2013-11-11
Hello all,

I have following values in datatable.

uid1 varchar(100),
          TotalVisitors INT,
          TotalOrders INT,
          TotalRevenue decimal(18,2),
          ProductRevenue decimal(18,2),
          ShippingCost decimal(18,2),
          AvgOrderValue decimal(18,2),
          UIDDesc varchar(100),
          TotalItems INT

and I want to group the data table by UIDDesc. and I want to sum up all the columns except uid1.

I have used following Linq query because I found out that we can not use groupby directly on datatable.

I have 2 issue one my application is on framework 2.0 so I cant use Linq. can you please tell me what can I do to solve this problem without using linq.

and also I tried using linq and I have added the code below please let me know whats wrong with the code its not working.
var query = from rawdata in dt.AsEnumerable() 
                    group rawdata by rawdata.Field<string>("UIDDesc") into grp
                    orderby grp.Key
                    select new
                    {
                        UIDDesc = grp.Key,
                        TotalOrders = grp.Sum(r => r.Field<decimal>("TotalOrders")),
                        TotalRevenue = grp.Sum(r => r.Field<decimal>("TotalRevenue")),
                        TotalVisitors = grp.Sum(r => r.Field<decimal>("TotalVisitors")),
                        ProductRevenue = grp.Sum(r => r.Field<decimal>("ProductRevenue")),
                        ShippingCost = grp.Sum(r => r.Field<decimal>("ShippingCost")),
                        AvgOrderValue = grp.Sum(r => r.Field<decimal>("AvgOrdervalue")),
                        TotalItems = grp.Sum(r => r.Field<decimal>("TotalItems")),
                    };
                foreach (var grp in query)
                {
                    StringBuilder table = new StringBuilder();
                    table.Append(tablerow);
                    table.Replace("@uid@", grp.UIDDesc.ToString());
                    table.Replace("@orders@", grp.TotalOrders.ToString());
                    table.Replace("@visitors@", grp.TotalVisitors.ToString());
                    table.Replace("@itemcount@", grp.TotalItems.ToString());
                    table.Replace("@productrevenue@", grp.ProductRevenue.ToString());
                    table.Replace("@shippingrevenue@", grp.ShippingCost.ToString());
                    
                    TotalOrders += Convert.ToDecimal(grp.TotalOrders.ToString());
                    TotalRevenue += Convert.ToDecimal(grp.TotalRevenue.ToString());
                    ProductRevenue += Convert.ToDecimal(grp.ProductRevenue.ToString());
                    ShippingRevenue += Convert.ToDecimal(grp.ShippingCost.ToString());
                    TotalVisits += Convert.ToDecimal(grp.TotalVisitors.ToString());
                    TotalItems += Convert.ToDecimal(grp.TotalItems.ToString());
                    sb.Append(table.ToString());
                }

Open in new window

0
Comment
Question by:ravigosai
  • 4
  • 2
6 Comments
 
LVL 17

Accepted Solution

by:
ToAoM earned 250 total points
ID: 34884532
0
 

Author Comment

by:ravigosai
ID: 34884697
Can you please explain me how this will be helpful in my case. and Can you help me building similar kind of code for my datatable.
0
 

Author Comment

by:ravigosai
ID: 34884925
by the given query I am getting the results I want now when I am trying to return this values using table.replace I am getting error message. Please help me out if I am doing something wrong.

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 17

Expert Comment

by:ToAoM
ID: 34886221
What is the error message your're getting? Without some information on what you're doing exactly, I can't really help you.
0
 

Assisted Solution

by:ravigosai
ravigosai earned 0 total points
ID: 34909664
I was able to solve the issue. I was required to write the query in different format I am writing the right query in this window.

I was able to solve the issue. thank you.
var query = from rawdata in dt.AsEnumerable()
                        group rawdata by rawdata.Field<string>("UIDDesc") into grp
                        orderby grp.Key
                        select new
                        {
                            UIDDesc = grp.Key,
                            TotalOrders = grp.Sum(r => r.Field<int>("TotalOrders")),
                            TotalRevenue = grp.Sum(r => r.Field<decimal>("TotalRevenue")),
                            TotalVisitors = grp.Sum(r => r.Field<int>("TotalVisitors")),
                            OtherVisitors = grp.Sum(r => r.Field<int>("OtherVisitors")),
                            ProductRevenue = grp.Sum(r => r.Field<decimal>("ProductRevenue")),
                            ShippingCost = grp.Sum(r => r.Field<decimal>("ShippingCost")),
                            AvgOrderValue = grp.Sum(r => r.Field<decimal>("AvgOrdervalue")),
                            TotalItems = grp.Sum(r => r.Field<int>("TotalItems")),
                        };

                
           
            foreach (var group in query)
                {
                        string s = group.UIDDesc;
                        int to = group.TotalOrders;
                        int tv = group.TotalVisitors;
                        int ti = group.TotalItems;
                        int ov = group.OtherVisitors;
                        decimal tr = group.TotalRevenue;
                        decimal pr = group.ProductRevenue;
                        decimal sc = group.ShippingCost;
                        decimal avo = group.AvgOrderValue;
                        
                        StringBuilder table = new StringBuilder();
                        table.Append(tablerow);
                        if (s == null)
                        {
                            table.Replace("@uid@", "None");
                        }
                        else if (s == "-")
                        {
                            table.Replace("@uid@", "Undefined");
                             
                            tv += Convert.ToInt32(Visits_temp);
                            tv = tv - Convert.ToInt32(HitsLinkInfo["Non-Campaign"].ToString());
                            
                        }
                        else
                        {
                            table.Replace("@uid@", s.ToString());
                        }
                        
                        if (tv != 0)
                        {
                            conversion = Math.Round((Convert.ToDecimal(to.ToString()) * 100) / tv, 2);
                        }
                        else
                        {
                            conversion = 0;
                        }
                        //tv += ov;
                        table.Replace("@orders@", to.ToString());
                        table.Replace("@conversion@", conversion.ToString());
                        table.Replace("@visitors@", tv.ToString());
                        table.Replace("@itemcount@", ti.ToString());
                        table.Replace("@productrevenue@", Math.Round(Convert.ToDecimal(pr.ToString()), 2).ToString("n2"));
                        table.Replace("@shippingrevenue@", Math.Round(Convert.ToDecimal(sc.ToString()), 2).ToString("n2"));
                        table.Replace("@revenue@", Math.Round(Convert.ToDecimal(tr.ToString()), 2).ToString("n2"));


                        
                        TotalOrders += Convert.ToDecimal(to.ToString());
                        TotalRevenue += Convert.ToDecimal(tr.ToString());
                        ProductRevenue += Convert.ToDecimal(pr.ToString());
                        ShippingRevenue += Convert.ToDecimal(sc.ToString());
                        TotalVisits += Convert.ToDecimal(tv.ToString());
                        
                        TotalItems += Convert.ToDecimal(ti.ToString());
                        sb.Append(table.ToString());
                    
                }

Open in new window

0
 

Author Closing Comment

by:ravigosai
ID: 34941356
I didnt get help on time so I was trying to sove the issue on my own. and I was able to find the soultion. so because of that reason I am choosing my comment as an answer. Please let me know if I am required to choose some other comment also and I will do that.

The link was not helpful in this context but still as expert tried to help so I am giving him partial credit.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

760 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

18 Experts available now in Live!

Get 1:1 Help Now