简体   繁体   English

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

[英]Count number of records for a certain condition with linq

I'm trying to retrieve some information form a table as follow: 我正在尝试从表格中检索一些信息,如下所示:

//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()
   };

Now, while this is working, i'm thinking there must be a better way of doing it. 现在,尽管这样做有效,但我认为必须有一种更好的方法。 Can someone suggest some better code? 有人可以建议一些更好的代码吗?

Thanks 谢谢

This should do the same: 该操作应相同:

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),
                  });

The Age and Weight aggregations seem a little uncanny - they are counting the number of records in each group where the associated property is not null. Age和“权Weight聚合似乎有点不可思议-它们计算的是相关属性不为null的每个组中的记录数。 Was this your intention, or were you after something like an "Average Age" of fish in each group? 这是您的意图,还是您在追求每组鱼类的“平均年龄”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM