Grouping by range of values ​​using linq and entity structure

I need data aggregated by age range, for example:

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

In my linq query, I use EntityFunctions.DiffYears to get age by date of birth:

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

however, if I group the group by age, I get 19,20,21 ... rather than ranges. What is the recommended way to accomplish this using the linq and entity framework?

+4
source share
1 answer

There are two ways to do this:

Process grouping on client

First create a group by age, as described, then use linq for the objects in the result to match the age with the age range, and then group by age range. See Grouping by an integer range of variables using Linq

Process grouping on server

Define a storage procedure that binds age to an age range (for example, returns 0 for ages 0 to 13, 1 for 14-19, etc.), and then use this storage procedure in your query.

+4
source

Source: https://habr.com/ru/post/1436009/


All Articles