0
有一个表在数据库:LINQ到SQL查询与GROUP BY
[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)
它给出了一个例外方法“的Int32 calculateAge(System.DateTime)'不支持对SQL的转换。 – Novikoff
我对LinqToSql不是很熟悉。但我假设在你的解决方案中,首先在SQL端进行分组,并在.NET端进行选择。而在我的解决方案中,有一组是按_after_选择的。 – Aleksei