Solved

LINQ - Groupby datatable & sum C#

Posted on 2011-02-13
6
2,875 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
[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
  • 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
I need help setting tabindex to textboxes in my MVC.Net application 3 24
WPF Select Items 3 27
orderby list (from Json) 1 30
Selenium and Xpath 4 32
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

733 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