Solved

LINQ - Groupby datatable & sum C#

Posted on 2011-02-13
6
2,830 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:
Jesse Houwing 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 17

Expert Comment

by:Jesse Houwing
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

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

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

Suggested Solutions

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
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…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

837 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