按年龄对用户进行分组以获取统计信息
Group users by age for stats
首先,我的问题与 this one 非常相似。事实上,这是一回事,只是我需要像下面这样对每个用户进行分组:
- 12 岁以下的所有人(不含)
- 然后,从 12 - 19
- 然后,从 20 - 29
- ...
- 80多个(含)
根据dasblinkenlight在另一个问题中的回答,我能够做到:
var ageStats = vModel
.GroupBy(l => 10 * (l.Age / 10))
.OrderBy(x => x.Key)
.Select(g => new
{
Name = g.Key,
Count = g.Select(l => l.Age).Count()
}).ToList();
对于结果集:
- 0-9
- 10-19
- 20-29
- ...
那么我应该怎么做才能完成我必须完成的模式?
非常感谢!!
试试这个,但我不知道性能
var ages = new int[12, 19, 29, 80];
var func = new Func<int, int>(a=>{
for(var i = 0; i<ages.Length; i++){
if(a<ages[i])
continue;
return i;
}
return 0;
});
vModel.GroupBy(m=>func(m.Age))....
您可以使用提到的方法 here 并使用此代码:
var ages = new List<int> { 12, 19, 29, 39, 49, 59, 69, 80, int.MaxValue};
var categories = vModel.GroupBy(item => ages.FirstOrDefault(ceil => ceil >= item));
var ages = new[] { 12, 19, 29, 80 };
var grouped = ages.Select(r => new {
Name = r,
Count = vModel.Count(x => x.Age >= r)
});
首先,我的问题与 this one 非常相似。事实上,这是一回事,只是我需要像下面这样对每个用户进行分组:
- 12 岁以下的所有人(不含)
- 然后,从 12 - 19
- 然后,从 20 - 29
- ...
- 80多个(含)
根据dasblinkenlight在另一个问题中的回答,我能够做到:
var ageStats = vModel
.GroupBy(l => 10 * (l.Age / 10))
.OrderBy(x => x.Key)
.Select(g => new
{
Name = g.Key,
Count = g.Select(l => l.Age).Count()
}).ToList();
对于结果集:
- 0-9
- 10-19
- 20-29
- ...
那么我应该怎么做才能完成我必须完成的模式?
非常感谢!!
试试这个,但我不知道性能
var ages = new int[12, 19, 29, 80];
var func = new Func<int, int>(a=>{
for(var i = 0; i<ages.Length; i++){
if(a<ages[i])
continue;
return i;
}
return 0;
});
vModel.GroupBy(m=>func(m.Age))....
您可以使用提到的方法 here 并使用此代码:
var ages = new List<int> { 12, 19, 29, 39, 49, 59, 69, 80, int.MaxValue};
var categories = vModel.GroupBy(item => ages.FirstOrDefault(ceil => ceil >= item));
var ages = new[] { 12, 19, 29, 80 };
var grouped = ages.Select(r => new {
Name = r,
Count = vModel.Count(x => x.Age >= r)
});