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

x
?
Solved

LINQ - Groupby datatable & sum C#

Posted on 2011-02-13
6
Medium Priority
?
3,090 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 1000 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
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

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…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

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