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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With