简体   繁体   中英

How do you select multiple aggregates and a non aggregate in LINQ

I have this TSQL statement which seems simple enough

select qGroup, AVG(score), COUNT(score)
  from [Scores]
  where [year] = 2014 and charIndex('s', qGroup, 0) <> 1
  group by qGroup

However, I just cannot figure out how to express this in LINQ (dot notation)

Here is my failed stab at it

List<qGroupModel> query = context.Scores.Where(p => (p.schoolID == schoolID) && (p.Year == year) && !(p.qGroup.StartsWith("S"))).Select(p => new { p.Average(p2 => p2.Score), p.qGroup }).GroupBy(p => p.qGroup).ToList<qGroupModel>();

The error I get from the above is as follows

'Models.Score' does not contain a definition for 'Average' and no extension method 'Average' accepting a first argument of type 'Models.Score' could be found (are you missing a using directive or an assembly reference?)

My LINQ acumen is not so great.. but still.. this seems harder than it should.

Please help

You can try this way :

List<qGroupModel> query = 
                    context.Scores
                           .Where(p => (p.schoolID == schoolID) && (p.Year == year) && !(p.qGroup.StartsWith("S")))
                           .GroupBy(p => p.qGroup)
                           .Select(p => new qGroupModel { p.Average(p2 => p2.Score), p.qGroup })
                           .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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