如何通过分组获取年龄分布列表 [英] How do I get Age distribution list by grouping
问题描述
我想要返回一个列表,其中包含与年龄分布相关的数据(例如,0-9岁,有10人,10-19岁,有7人等)
这是我的查询: -
public List< ReportHelper> GetAgeDistribution(int userId)
{
var itemList =(from this.ObjectContext.TreeMembers
其中item.UserId == userId
group(DateTime.Now - (item。 (DateTime.Now - (item.Birthdate ?? DateTime.Now))。天数/ 365.25)/ 9);日期/ 365.25
列表< ReportHelper> list = new List< ReportHelper>();
foreach(itemList中的var item)
list.Add(new ReportHelper {Data = item.Count(),Label = item.Key + - +(item.Key + 9 )});
返回列表;
}
当我运行这个查询我得到dbarithmeticexpression异常:
DbArithmeticExpression参数必须具有数字通用类型。
如何解决这个错误?我知道实体框架4不能将我的表达式翻译成普通的旧的sql。我如何提示我想做什么?
提前感谢:)
此外,您将年龄分成小桶的逻辑 [0 - 9]
年, [10 - 19]
年等似乎不正确;您应该将完整的年份除以 10
而不是 9
。
此查询应该正常工作:
var itemList = from item在this.ObjectContext.TreeMembers
其中item.UserId == userId
let age = EntityFunctions.DiffYears
(item.Birthdate,DateTime.Now)? 0
按年龄/ 10分组项目到ageGroup
选择新
{
AgeInCompletedDecades = ageGroup.Key,
Count = ageGroup.Count()
} ;
I want to return a List which contains data related to the Age Distribution (Eg. For Age 0-9 there are 10 persons, for 10-19 there are 7 persons etc)
This is my query :-
public List<ReportHelper> GetAgeDistribution(int userId)
{
var itemList = (from item in this.ObjectContext.TreeMembers
where item.UserId == userId
group (DateTime.Now - (item.Birthdate ?? DateTime.Now)).Days/365.25
by ((DateTime.Now - (item.Birthdate ?? DateTime.Now)).Days / 365.25) / 9);
List<ReportHelper> list = new List<ReportHelper>();
foreach (var item in itemList)
list.Add(new ReportHelper { Data = item.Count(), Label = item.Key + "-" + (item.Key + 9) });
return list;
}
When I run this query I get dbarithmeticexpression exception :
DbArithmeticExpression arguments must have a numeric common type.
How do I solve this error? I know Entity Framework 4 is not able to translate my expression to plain old sql. How can I hint it what I am trying to do?
Thanks in advance :)
Saeed is right; the best way to go here is to use the canonical DiffYears
function through the EntityFunctions.DiffYears
method.
In addition, the logic you have for dividing ages into the buckets [0 - 9]
years, [10 - 19]
years etc. seems incorrect; you should divide complete years by 10
, not 9
.
This query should work fine:
var itemList = from item in this.ObjectContext.TreeMembers
where item.UserId == userId
let age = EntityFunctions.DiffYears
(item.Birthdate, DateTime.Now) ?? 0
group item by age / 10 into ageGroup
select new
{
AgeInCompletedDecades = ageGroup.Key,
Count = ageGroup.Count()
};
这篇关于如何通过分组获取年龄分布列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!