如何在Linq查询中获取日期和总日期

时间:2015-03-27 08:25:01

标签: c# linq entity-framework

我正在尝试查询我的SQL Server数据库以获取最近的日期和每个日期的条目数。

我的努力是(其中_dc是我的DataContext)

var result = (from d in this._dc.MyTable
                      where d.DateTime >= fromDate
                      group d by d.DateTime into g
                      select g.FirstOrDefault()).ToDictionary(a => a.DateTime, a => a.Id);

这会产生结果,但会产生Dictionary DateTimeIdId不正确,我只是为了测试

我的努力所产生的数据是

Dictionary<01/01/2015 10:09:33, 1>
Dictionary<01/01/2015 11:55:12, 2>
Dictionary<02/01/2015 08:11:45, 3>
Dictionary<03/01/2015 10:10:14, 4>
Dictionary<03/01/2015 12:00:32, 5>

我想要返回的数据是(注意唯一日期,因为它忽略了时间)

Dictionary<01/01/2015, 2>
Dictionary<02/01/2015, 1>
Dictionary<03/01/2015, 3>
Dictionary<04/01/2015, 4>
Dictionary<05/01/2015, 3>

左边是进入日期,右边是累计访问量。

我尝试过像

这样的事情
.ToDictionary(a => a.DateTime, a => a.DateTime.Sum()); //compiler issue

我迷路了,有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用分组本身作为字典的输入:

(from d in this._dc.MyTable
                  where d.DateTime >= fromDate
                  group d by DbFunctions.TruncateTime(d.DateTime) into g
                  select g)
.ToDictionary(g => g.Key, g => g.Count());

使用实体框架&lt; v6,EntityFunctions应该用来代替DbFunctions

相关问题