Group by,并汇总求和
static void Main(string[] args) { bbb(); Console.ReadKey(); } public static List<Dto> toAdd() { List<Dto> dtos = new List<Dto>(); Dto dto1 = new Dto() { uid = 001, value = 1, type = "add" }; Dto dto2 = new Dto() { uid = 001, value = 1, type = "no" }; Dto dto3 = new Dto() { uid = 001, value = 1, type = "no" }; Dto dto4 = new Dto() { uid = 001, value = 1, type = "no" }; Dto dto5 = new Dto() { uid = 002, value = 1, type = "add" }; Dto dto6 = new Dto() { uid = 002, value = 1, type = "add" }; Dto dto7 = new Dto() { uid = 002, value = 1, type = "add" }; Dto dto8 = new Dto() { uid = 002, value = 1, type = "add" }; dtos.Add(dto1); dtos.Add(dto2); dtos.Add(dto3); dtos.Add(dto4); dtos.Add(dto5); dtos.Add(dto6); dtos.Add(dto7); dtos.Add(dto8); return dtos; } private static List<Dto> aaa() { var dtos = toAdd(); foreach (var item in dtos) { if (item.type == "no") { item.value = -item.value; } } return dtos; } private static IEnumerable bbb() { var dtos = aaa(); var nResult = dtos.GroupBy(a => new { a.uid }) .Select(g => new { uid=g.Key.uid, value=g.Sum(x=>x.value) }); return nResult; }
///Entity Framework Lambda 实现多列Group by,并汇总求和
///参考https://www.cnblogs.com/xuxu-dragon/p/3824427.html
var result = DataSummaryRepository.FindBy(x => x.UserID == argMemberNo && x.SummaryDate <= argEndDate && x.SummaryDate >= argStarDate).OrderByDescending(x => x.SummaryDate).GroupBy(x => new { x.SummaryDate, x.UserID }).Select(g => new { PV = g.Sum(x => x.PV), UV = g.Sum(x => x.UV), OrderQunantity = g.Sum(x => x.OrderQunantity), OrderAmount = g.Sum(x => x.OrderAmount), CommissionEstimate = g.Sum(x => x.CommissionEstimate), AvaliableCommission = g.Sum(x => x.AvaliableCommission), HistoryCommission = g.Sum(x => x.HistoryCommission), SummaryDate = g.Key.SummaryDate, UserID = g.Key.UserID });