数据库中有一个表:
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](150) NOT NULL,
[date_of_birth] [date] NOT NULL,
我需要为GridView获取一个包含2列的数据源。
----------------
| age || count |
----------------
| 20 || 3 |
| 21 || 4 |
| 25 || 5 |
----------------
是否可以通过一个查询来完成?
我尝试了什么:
var dates = (from u in db.Users
group u by u.date_of_birth into g
select new { age = calculateAge(g.Key) }).ToList();
var dates1 = from d in dates
group d by d.age into g
select new { age = g.Key, count = g.Count() };
GridView1.DataSource = dates1;
GridView1.DataBind();
这有效,但我认为有一种方法可以使它更简单。或者不是?
P.S。 calculateAge具有以下签名
private int calculateAge(DateTime date_of_birth)
答案 0 :(得分:1)
以下是我对您的疑问(计算年龄相同的人数):
var dates = from u in db.Users
select new { age = calculateAge(g.Key) } into ages
group ages by ages.age into g
select new { age = g.Key, count = g.Count() };
甚至没有匿名类型声明:
var dates = from u in db.Users
select calculateAge(g.Key) into ages
group ages by ages into g
select new { age = g.Key, count = g.Count() };