0

以下查询有效,但我想在不使用 grp.Sum() 的情况下获得相同的结果。我们能做到吗?

from item in (await VehicleReplaceCostDataAsync())
                group item by (item.type, item.size, item.ADA, item.eseq) into grp
                orderby (grp.Key.eseq, grp.Key.size, grp.Key.ADA)
                select new VehicleReplacementCost
                {
                    type = grp.Key.type,
                    size = grp.Key.size,
                    ADA = grp.Key.ADA,
                    count = grp.Sum(x => x.count),
                    cost = grp.Sum(x => x.cost),
                    Fcount = grp.Sum(x => x.Fcount),
                    Fcost = grp.Sum(x => x.Fcost),
                    eseq = grp.Key.eseq,
                }).ToList();
4

2 回答 2

1

也许通过使用.Aggregate()?[文档]

count = grp.Aggregate(0, (a, b) => a + b.count)
于 2022-02-09T18:07:14.770 回答
0

感谢 Astrid 的回答。它看起来不错,但我没有测试它。我的同事使用 yield 代替了这个解决方案:

var groups = costs
                .GroupBy(type => (type.SystemId, type.Type, type.Size, type.ADA, type.Eseq))
                .OrderBy(group => (group.Key.SystemId, group.Key.Eseq, group.Key.Size, group.Key.ADA));

 

            foreach (var group in groups)
            {
                var result = new ProgramGuideVehicleCostRow
                {
                    SystemId = group.Key.SystemId,
                    Type = group.Key.Type,
                    Size = group.Key.Size,
                    ADA = group.Key.ADA,
                };
                foreach (var row in group)
                {
                    result.Cost += row.Cost;
                    result.Fcost += row.Fcost;
                    result.Count += row.Count;
                    result.Fcount += row.Fcount;
                }
                yield return result;
            }
于 2022-02-09T20:23:16.410 回答