Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- LINQ GroupBy DateTime dilemma
- public IDictionary<string, int> GetCountByDate(DateTime fromDate, DateTime toDate)
- {
- var result = Database.Set<User>().Where(x => x.CreatedAt >= fromDate && x.CreatedAt <= toDate).GroupBy(x => new { x.CreatedAt.Year, x.CreatedAt.Month, x.CreatedAt.Day }).Select(x => new { Date = x.Key, Count = x.Count() });
- return result.ToDictionary(x => new DateTime(x.Date.Year, x.Date.Month, x.Date.Day).ToShortDateString(), x => x.Count);
- }
- return result.ToDictionary(x => new DateTime(x.Date.Year, x.Date.Month, x.Date.Day).ToLocalTime().ToShortDateString(), x => x.Count);
- public IDictionary<string, int> GetCountByDate(DateTime fromDate, DateTime toDate)
- {
- DateTime utcFrom = fromDate.ToUniversalTime();
- DateTime utcTo = toDate.ToUniversalTime();
- int offset = (int)(fromDate - utcFrom).TotalHours;
- var result = Database.Set<User>().Where(x => x.CreatedAt >= utcFrom && x.CreatedAt <= utcTo)
- .GroupBy(x => new {
- SqlFunctions.DateAdd("hh", offset, x.CreatedAt).Value.Year,
- SqlFunctions.DateAdd("hh", offset, x.CreatedAt).Value.Month,
- SqlFunctions.DateAdd("hh", offset, x.CreatedAt).Value.Day })
- .Select(x => new { Date = x.Key, Count = x.Count() });
- return result.ToDictionary(x => new DateTime(x.Date.Year, x.Date.Month, x.Date.Day).ToShortDateString(), x => x.Count);
- }
Add Comment
Please, Sign In to add comment