Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a datatable of 3 columns.
C#
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.
C#
Category |  Counts
--------------------------------
1        |  202
2        |  295
3        |  36



C#
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

C#
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)});
 
Share this answer
 
v5
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.
 
Share this answer
 
I think using .Sum() function instead of .FirstOrDefault() will help you
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900