I would like to get the total order amount for each customer with Linq, I know I need to group and sum I have only succeeded to group without summing the whole amount for each order.
var OrderByCustumer = new[] {
new { name = "cust1", order = 400 },
new { name = "cust1", order = 250 },
new { name = "cust1", order = 130 },
new { name = "cust2", order = 30 },
new { name = "cust3", order = 205}
};
var res= OrderByCustumer.GroupBy(x=>x.name).Select((x,y)=>new{
a=x.Key
});
foreach(var a in res){
Console.WriteLine(a);
}
.**
OutPut
a = cust1
a = cust2
a = cust3
**
CodePudding user response:
Try this
var res = OrderByCustumer.GroupBy(x => x.name).Select(x => new {
a = x.Key,
sum = x.Sum(c => c.order)
});
foreach (var item in res)
{
Console.WriteLine($"{ item.a} - Sum = {item.sum}");
}