LINQ Group by未返回预期结果,如何计算动物总费用?
解决LINQ计算动物总费用的问题
问题原因
你的原查询仅对Animals对象做了分组,但未保留关联的Cost数据用于计算,也没有做正确的结果投影。你看到仅返回Wolf大概率是因为未正确遍历或输出分组结果——实际上分组后应该包含三个动物类型的组,但需要提取数据并完成总费用计算。
正确的LINQ写法
方式一:先关联再分组计算
通过join关联两个列表后,将所需的Amount和Cost字段组合,分组后计算每条数据的费用乘积再求和:
var totalCost = from animal in animalList join cost in costList on animal.Type equals cost.AnimalType group new { animal.Amount, cost.Cost } by animal.Type into g select new { AnimalType = g.Key, TotalCost = g.Sum(item => item.Amount * item.Cost) };
方式二:先分组动物再关联费用
先按动物类型分组计算总数量,再关联费用表一次性计算总费用,这种方式更高效(每个类型仅关联一次费用数据):
var totalCost = from animalGroup in animalList.GroupBy(a => a.Type) join cost in costList on animalGroup.Key equals cost.AnimalType select new { AnimalType = animalGroup.Key, TotalCost = animalGroup.Sum(a => a.Amount) * cost.Cost };
结果验证
执行上述任一查询后,遍历结果即可得到预期数据:
| AnimalType | TotalCost |
|---|---|
| Wolf | 30000 |
| Lion | 20000 |
| Horse | 7500 |
原查询修改方案
如果要基于你最初的查询调整,只需在分组时保留关联的费用数据,并在select中完成计算:
var totalCost = from animal in animalList join cost in costList on animal.Type equals cost.AnimalType group new { animal, cost } by animal.Type into g select new { AnimalType = g.Key, TotalCost = g.Sum(item => item.animal.Amount * item.cost.Cost) };
内容的提问来源于stack exchange,提问作者Cenderze
相关产品推荐
相关产品推荐

