我正在尝试从表中检索一些信息,如下所示:
//Fish table: fishid(int32), SpeciesName(nvarchar(50)),age(int?), weight(int?)
(from f in Fish
where f.SpeciesName=="COD" || f.SpeciesName=="Salmon"
select f
).GroupBy(g=>g.SpeciesName)
.Select(s= > new
{
Species=s.Key,
Age= (from age_count in Fish where age_count.SpeciesName== s.key && age_count.age!=null select age_count).Count(),
Weight= (from Weight_count in Fish where Weight_count.SpeciesName== s.key && Weight_count.Weight!=null select weight_count).Count()
};
现在,虽然这是有效的,但我认为必须有更好的方法。 有人可以建议一些更好的代码吗?
由于
答案 0 :(得分:5)
这应该做同样的事情:
var result = Fish.Where(f => f.SpeciesName == "COD" || f.SpeciesName == "Salmon")
.GroupBy(f => f.SpeciesName)
.Select(g => new {
Species = g.Key,
Age = g.Count(f => f.Age != null),
Weight= g.Count(f => f.Weight != null),
});
Age
和Weight
聚合看起来有点不可思议 - 它们正在计算关联属性不为空的每个组中的记录数。这是你的意图,还是你在追求每组鱼的“平均年龄”之类的东西?