4

I need some data aggregated by age range, something like:

 Age    |   Members
 ------------------
 0-13   |   150
 14-19  |   250
 20-30  |   400

In my linq query I'm using EntityFunctions.DiffYears to get age based on birth date:

let age = EntityFunctions.DiffYears(contact.Birthday, today)

however if I group group by the age field I will get 19,20,21... and not the ranges. What is the recommended way to acomplish this with linq and entity framework?

CodeMaster2008
  • 921
  • 2
  • 13
  • 25

1 Answers1

4

There are two ways of doing this:

Process the grouping on client

First group them by age as you described, then use linq to objects on the result to map the age to an age range and then group by age range. See Group by variable integer range using Linq

Process the grouping on the server

Define a store procedure that would map the age to an age range (e.g. return 0 for ages between 0 and 13, 1 for 14-19 and so on) and then use this store procedure in your query.

Community
  • 1
  • 1
Andriy Svyryd
  • 2,021
  • 1
  • 19
  • 26