Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have a Product class with
ProductName
Category
Price

and I want to display an information like this:

ProductName | Category | Price

XXXVVVXXXX         |   Category1    |    10
XXYZXXXXXX       |  Category1     |   15

Total Category1:     35

YYYY    |    Category2   |     05
YYVV    |   Category2    |   10
TTTT    |  Category2      |   11

Total Category2:     26

Total All Categories 61


How could I do this using Linq ?
I appreciate all suggestions.
I'm using asp.net MVC 4.
Posted
Updated 18-Mar-14 2:44am
v2

1 solution

Perhaps something like this?
C#
var query =
    from p in Products
    group p by p.Category into g
    select new { Category = g.Key, Total = g.Sum(p => p.Price), Values = g };


See it working:
http://ideone.com/ckhFNq

But it would be more efficient just to calculate the total with a for-loop.
 
Share this answer
 
Comments
Maciej Los 24-Mar-14 16:35pm    
Good answer, but i must to disagree with this part: But it would be more efficient just to calculate the total with a for-loop
Dennis_E 26-Mar-14 5:07am    
Yeah, I don't know what I was thinking there... Never mind that part.

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