Click here to Skip to main content
14,239,312 members
Rate this:
Please Sign up or sign in to vote.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

Perhaps something like this?
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.
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100