Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should i use group by and sum on different values of list of models using linq

I have FinalCons which is a list of my model class

List<ItemsConsumed> FinalCons = new List<ItemsConsumed>(); 

This FinalCons has a list of Item Consumed by the persons, Like

Content of FinalCons List

And I want List in which the data should be like this, Needed List after group by and sum

I tried this, But sum is not calculating properly.

 var itemcomsumed = FinalCons.OrderBy(x => x.PersonalID).ToList().GroupBy(x => x.PersonalID)
            .Select(x => new 
            { 
                consumption = x.Sum(a => a.Consumption), 
                PersonalID= x.Select(a => (int)a.PersonalID), 
                ItemID = x.Select(a => (int)a.ItemID)
            });

i also tried to get the required result from this, but this also not giving me the correct result.

var itemCon = FinalCons.GroupBy(ic => new { ic.PersonalID}).Select(ic => new ItemsConsumed
           {
              PersonalID=ic.Key.PersonalID,
               ItemID = ic.FirstOrDefault().ItemID,
               Consumption=ic.Sum(c=>c.Qty)
           }).ToList();
like image 419
Pooja K. Avatar asked Dec 07 '25 21:12

Pooja K.


1 Answers

Your final list is grouped by both PersonalID and ItemID,

<Personal ID, Item ID, Consumption>

<1 , 4 , 1>        <1 , 4 , 2>         
<1 , 4 , 1>        <1 , 5 , 1>         
<1 , 5 , 1>        <2 , 4 , 1>         
<2 , 4 , 1>        <2 , 5 , 2>        
<2 , 5 , 2>                      

Use the below grouping logic

var itemConsumed = FinalCons
                   .GroupBy(x => new { 
                               x.PersonalID, 
                               x.ItemID 
                   }) //group by both PersonalID and ItemID
                   .Select(x => new 
                   { 
                       PersonalID= x.Key.PersonalID, 
                       ItemID = x.Key.ItemID,
                       Consumption = x.Sum(a => a.Consumption)
                   })
                   .OrderBy(x => x.PersonalID).ThenBy(y=>y.ItemID);
                     //order by Personal ID and then by Item ID
like image 83
Shaunak D Avatar answered Dec 09 '25 15:12

Shaunak D