我正在尝试查询我的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
DateTime
和Id
。 Id
不正确,我只是为了测试
我的努力所产生的数据是
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
我迷路了,有什么想法吗?
答案 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
。