需求:计算出每个商品类型的价格总和
最终结果:
类型:{ goodType = 衣物 },总价格:600
类型:{ goodType = 电子 },总价格:900
类型:{ goodType = 废品 },总价格:600
class sku_location
{
public string goodType { get; set; }
public string goodName { get; set; }
public int price { get; set; }
public int sum { get; set; }
}
static void Main(string[] args)
{
List<sku_location> datas = new List<sku_location>();
datas.Add(new sku_location { goodType = "衣物", goodName = "衣物1", price = 100 });
datas.Add(new sku_location { goodType = "衣物", goodName = "衣物2", price = 200 });
datas.Add(new sku_location { goodType = "衣物", goodName = "衣物3", price = 300 });
datas.Add(new sku_location { goodType = "电子", goodName = "电子1", price = 400 });
datas.Add(new sku_location { goodType = "电子", goodName = "电子2", price = 500 });
datas.Add(new sku_location { goodType = "废品", goodName = "废品1", price = 600 });
var responseData = datas
.GroupBy(a => new { a.goodType })
.Select(sku => new { goodType = sku.Key, sum = sku.Sum(s => s.price) }).ToList();
for (int i = 0; i < responseData.Count; i++)
{
Console.WriteLine("类型:" + responseData[i].goodType + ",总价格:" + responseData[i].sum);
}
Console.ReadKey();
}