Guest User

Untitled

a guest
Aug 17th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. LINQ GroupBy DateTime dilemma
  2. public IDictionary<string, int> GetCountByDate(DateTime fromDate, DateTime toDate)
  3. {
  4. 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() });
  5.  
  6. return result.ToDictionary(x => new DateTime(x.Date.Year, x.Date.Month, x.Date.Day).ToShortDateString(), x => x.Count);
  7. }
  8.  
  9. return result.ToDictionary(x => new DateTime(x.Date.Year, x.Date.Month, x.Date.Day).ToLocalTime().ToShortDateString(), x => x.Count);
  10.  
  11. public IDictionary<string, int> GetCountByDate(DateTime fromDate, DateTime toDate)
  12. {
  13. DateTime utcFrom = fromDate.ToUniversalTime();
  14. DateTime utcTo = toDate.ToUniversalTime();
  15. int offset = (int)(fromDate - utcFrom).TotalHours;
  16. var result = Database.Set<User>().Where(x => x.CreatedAt >= utcFrom && x.CreatedAt <= utcTo)
  17. .GroupBy(x => new {
  18. SqlFunctions.DateAdd("hh", offset, x.CreatedAt).Value.Year,
  19. SqlFunctions.DateAdd("hh", offset, x.CreatedAt).Value.Month,
  20. SqlFunctions.DateAdd("hh", offset, x.CreatedAt).Value.Day })
  21. .Select(x => new { Date = x.Key, Count = x.Count() });
  22.  
  23. return result.ToDictionary(x => new DateTime(x.Date.Year, x.Date.Month, x.Date.Day).ToShortDateString(), x => x.Count);
  24. }
Add Comment
Please, Sign In to add comment