Click here to Skip to main content
14,300,703 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have a datatable of 3 columns.
Category | Product | Counts
--------------------------------
1        |  Tea    | 100
1        |  Cofee  | 102
2        |  Pen    | 23
2        |  Den    | 200
2        |  Wen    | 60
2        |  Gen    | 12
3        |  Tip    | 12
3        |  Gip    | 12
3        |  Dip    | 12


i want to group it by category with LINQ and show the sum of the Counts(column) under Category

e.x.
Category |  Counts
--------------------------------
1        |  202
2        |  295
3        |  36



DataTable MainData = obj.DATA();

        var query = from b in MainData.AsEnumerable()

                   group b by  b.Field<string>("Category")  into Grp
                   let _count =  Convert.ToInt32( Grp.FirstOrDefault().Field<string>("_count")) 
                                 
                  orderby __count descending
                  select new
                         {
                             Category= Grp.Key,
                          Count = _count
                         };


its just counting the rows.
Posted
Updated 29-May-14 0:47am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

This link http://social.msdn.microsoft.com/Forums/en-US/3b13432a-861e-45f0-8c25-4d54622fbfb4/linq-group-and-sum-table?forum=linqprojectgeneral[^] should give you the solution to your problem.

Part of your issue is that you aren't actually doing a sum in your linq.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

var result = MainData.AsEnumerable()
.Select(r=> new{ Category = r.Field<string>("Category"), 
                 Count =Convert.ToInt32( r.Field<string>("_count"))})
.GroupBy(x=>x.Category).Select(g=>new{Category=g.Key, Count=g.Sum(c=>c.Count)});
   
v5
Rate this:
Please Sign up or sign in to vote.

Solution 3

I think using .Sum() function instead of .FirstOrDefault() will help you
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100