Solved

LINQ - Groupby datatable & sum C#

Posted on 2011-02-13
6
2,813 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

776 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