使用linq计算特定条件的记录数

Mee*_*mfp 1 c# linq

我正在尝试从表中检索一些信息,如下所示:

//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()
   };
Run Code Online (Sandbox Code Playgroud)

现在,虽然这是有效的,但我认为必须有更好的方法.有人可以建议更好的代码吗?

谢谢

Jam*_*iec 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),
                  });
Run Code Online (Sandbox Code Playgroud)

AgeWeight聚合似乎有点不可思议-他们每一组中的相关属性不为null计算中的记录数.这是你的意图,还是你在追求每组鱼的"平均年龄"之类的东西?