0

I have an entity i would say it as "Items", Structure of this entity like below,

string itemName
int groupId
decimal itemPrice
int itemQty

first i wanted to group it by groupId and return it as a list of list of items (List<List<Items>>) I followed this instruction and successfully did it. Using Linq to group a list of objects into a new grouped list of list of objects

Here is my code to get that List<List<Item>>

var groupedItem = rawItemData               
        .GroupBy(u => u.groupId)             
        .Select(grp => grp.ToList())          
        .ToList();

But now i want to order each group(list) by getting summation of itemPrice on it.

Example for my expectation:

  • 1st element of my result has 5 Items, Summation of item price in this group is 350
  • 2nd element of my result has 10 Items, Summation of item price in this group is 500
  • 3rd element of my result has 2 Items, Summation of item price in this group is 150
  • 4th element of my result has 6 Items, Summation of item price in this group is 555

I want to group my main result by this summation of item price,

Expected order is like below, 4th element, 2nd element, 1st element, 3rd element.

Something very hard to explain, Please let me know if need more clarification on this question.

Thank you very much!

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
  • Can you put the content of `rawItemData` here? It will be easier to understand – Ozkan Jan 15 '19 at 20:10
  • rawItemData = List Example: 1. itemName : Test 1 groupId : 1 itemPrice: 10 itemQty : 3 2. itemName : Test 2 groupId : 1 itemPrice: 12 itemQty : 4 3. itemName : Test 3 groupId : 2 itemPrice: 13 itemQty : 4 4. itemName : Test 4 groupId : 2 itemPrice: 55 itemQty : 3 Like this – Sithija Sahan Jan 15 '19 at 20:12
  • 3
    I think you want a `.OrderByDescending(grp => grp.Sum(x => x.itemPrice))` after the `GroupBy`. – juharr Jan 15 '19 at 20:15
  • Sorry i will add it in the main question – Sithija Sahan Jan 15 '19 at 20:15
  • Check this: https://stackoverflow.com/a/16522841/1410501 – Ozkan Jan 15 '19 at 20:17
  • 2
    I think you want the total price of the group.. so.. `.OrderByDescending(grp => grp.Sum(x => x.itemPrice * x.itemQty))` – Leo Bartkus Jan 15 '19 at 20:19
  • @juharr Great! I checked your code snippet now, That is what i expected Thank you very much.... I can mark your answer as the best if you posted it as a answer to this. – Sithija Sahan Jan 15 '19 at 20:27

0 Answers0