Lambda GroupBy 跟 Sum的筆記
範例是把每一天的數量各自加總
測試資料
class Order
{
public int OrderId { get; set; }
public string GoodsName { get; set; }
public DateTime? SoldTime { get; set; }
public int? Quantity { get; set; }
}
class SeedData
{
public SeedData()
{
this.GenerateOrders = new List<Order>();
string JsonOrders
//3月11日
= "[{\"OrderId\":0,\"GoodsName\":\"Tea\",\"Quantity\":3,\"SoldTime\":\"2019/03/11 10:21:32\"},"
+ "{\"OrderId\":1,\"GoodsName\":\"Tea\",\"Quantity\":5,\"SoldTime\":\"2019/03/11 17:13:09\"},"
+ "{\"OrderId\":2,\"GoodsName\":\"Tea\",\"Quantity\":10,\"SoldTime\":\"2019/03/11 22:01:56\"},"
//3月13日
+ "{\"OrderId\":3,\"GoodsName\":\"Milk\",\"Quantity\":5,\"SoldTime\":\"2019/03/13 09:13:09\"},"
+ "{\"OrderId\":4,\"GoodsName\":\"Milk\",\"Quantity\":15,\"SoldTime\":\"2019/03/13 10:00:22\"},"
+ "{\"OrderId\":5,\"GoodsName\":\"Milk\",\"Quantity\":20,\"SoldTime\":\"2019/03/13 11:00:33\"},"
//3月16日
+ "{\"OrderId\":6,\"GoodsName\":\"Soda\",\"Quantity\":5,\"SoldTime\":\"2019/03/16 13:11:44\"},"
+ "{\"OrderId\":7,\"GoodsName\":\"Soda\",\"Quantity\":7,\"SoldTime\":\"2019/03/16 14:11:55\"}]";
GenerateOrders
= JsonConvert.DeserializeObject<List<Order>>(JsonOrders);
}
public List<Order> GenerateOrders { get; set; }
}
正片開始
class Program
{
static void Main(string[] args)
{
SeedData seedData = new SeedData();
List<Order> viewModel = new List<Order>();
viewModel = seedData.GenerateOrders;
List<Order> OrderList = viewModel.GroupBy(x => new {
SoldTime = x.SoldTime.GetValueOrDefault().Date,
GoodsName = x.GoodsName
}).Select(x => new Order
{
GoodsName = x.Key.GoodsName,
SoldTime = x.Key.SoldTime,
Quantity = x.Sum(y => y.Quantity)
}).ToList();
foreach (var item in OrderList)
{
Console.WriteLine(JsonConvert.SerializeObject(item));
}
Console.ReadKey();
}
}
輸出結果