C# 选择并分组
我有一个包含以下字段的表C# 选择并分组,c#,linq,C#,Linq,我有一个包含以下字段的表 ID fk_siteID VisitDate 我想用LINQ编写一个查询,返回一天中具有特定SiteID的记录数。例如,如果siteid=1show me 12.1.2014 6 13.1.204 8 我写了这个查询 var n = from a in db.CompanyWebsiteUsers group a by EntityFunctions.TruncateTime(a.VisitDate) into g o
ID
fk_siteID
VisitDate
我想用LINQ编写一个查询,返回一天中具有特定SiteID
的记录数。例如,如果siteid=1
show me
12.1.2014 6
13.1.204 8
我写了这个查询
var n = from a in db.CompanyWebsiteUsers
group a by EntityFunctions.TruncateTime(a.VisitDate) into g
orderby g.FirstOrDefault().VisitDate
where g.FirstOrDefault().fk_siteID == WebsiteID
select new
{
key = g.Key,
dayofweek = SqlFunctions.DateName("weekday", g.Key),
count = g.Count()
};
grdDailyRes.DataSource = n;
grdDailyRes.DataBind();
显示此查询的结果:
当我的表中有2条记录时,这些记录的VisitDate
字段与siteid=1
和第二条siteid=2
相同。
如果
websiteid
为1或为2,则此查询将首先计算它们。您只检查组中的第一个项目,但还必须检查其他项目。最简单的解决方案是移动where语句,即
var n = from a in db.CompanyWebsiteUsers
where a.fk_siteID == WebsiteID
group a by EntityFunctions.TruncateTime(a.VisitDate) into g
orderby g.FirstOrDefault().VisitDate
select new