C# List GroupBy and Sum
List<PartRequest> partRequests = new List<PartRequest>(); partRequests.Add(new PartRequest() { factory = "f1", stock = "s1", material = "m1", quantity = 10 }); partRequests.Add(new PartRequest() { factory = "f1", stock = "s1", material = "m1", quantity = 20 }); partRequests.Add(new PartRequest() { factory = "f1", stock = "s2", material = "m1", quantity = 40 }); partRequests.Add(new PartRequest() { factory = "f2", stock = "s1", material = "m1", quantity = 10 }); partRequests.Add(new PartRequest() { factory = "f1", stock = "s1", material = "m2", quantity = 80 }); partRequests.Add(new PartRequest() { factory = "f2", stock = "s2", material = "m2", quantity = 120 }); partRequests.Add(new PartRequest() { factory = "f2", stock = "s2", material = "m2", quantity = 120 }); var materialGroup = partRequests.GroupBy(x => new { x.material }).Select(x => x.Key.material).ToList(); var groupedResult = partRequests.GroupBy(x=>string.Join(x.factory,":",x.stock,":",x.material)).ToList(); var groupByStckAndFactoryResult = partRequests.GroupBy(x => new { factory = x.factory, stock = x.stock}) .Select(y => new { factory = y.Key.factory, stock = y.Key.stock, material = y.First().material }).ToList(); var groupByStckAndFactoryAndMaterialResult = partRequests.GroupBy(x => new { factory = x.factory, stock = x.stock, material = x.material }) .Select(y => new { factory = y.Key.factory, stock = y.Key.stock, material = y.Key.material, quantity = y.Sum(i => i.quantity) }).ToList(); Console.WriteLine(materialGroup);
posted on 2022-12-06 11:17 Tencent/Tim 阅读(547) 评论(0) 编辑 收藏 举报