【发布时间】:2011-09-11 07:39:58
【问题描述】:
给定类:
public class FooAmounts
int Id
decimal Month1
decimal Month2
...
decimal Month12
decimal Year2
decimal Year3
decimal Future
我有 IEnumerable<FooAmounts> 有 5 个条目(ID 的 1-5 很有趣!)
我想创建一个新的 FooAmounts,其中包含每个月/年的总数,但仅限于 Id==1 + Id==2 例如
var footle = (from f in foolist
where f.Id == 1 || f.Id == 2
select new FooAmounts{
Month1 = Sum(month 1s),
Month2 = Sum(month 2s),
etc etc.
Future = Sum(futures)
).FirstOrDefault();
我正在尝试重新创建这个 t-sql:
select SUM(Month1) as Month1, SUM(Month2) as Month2, SUM(Month3) as Month3 from FooAmount where Id=1 or Id=2"
我可以使用group by f.Id into grp 子句实现类似的效果,但这给我留下了两个项目,因此我不能使用 First/FoD,这意味着我必须手动对它们求和......这似乎我必须失踪某处的诡计?
注意:FirstOrDefault() 仅存在于此,因此我返回单个对象而不是包含一个对象的可枚举。我认为(也许是错误的!)无论如何,这应该总是只返回一个项目...... Sum() 只有一个结果,无论有多少项目进入计算。
【问题讨论】: