linq to entity group by 時間

CreationTime是DateTime類型c#

group by 年/月/日/小時

group by 年code

(from d in YourData.OrderBy(x => x.CreationTime)
 group d by new
 {
     time = new { d.CreationTime.Year }
 } into g
 select new
 {
     AverageValue = g.Average(p => p.Value),
     CreationTimeStr = g.Key.time.Year,
     MaxValue = g.Max(x => x.Value),
     MinValue = g.Min(x => x.Value)
 }).ToList();

group by 小時get

(from d in YourData.OrderBy(x => x.CreationTime)
 group d by new
 {
     time = new { d.CreationTime.Year, d.CreationTime.Month, d.CreationTime.Day,d.CreationTime.Hour }
 } into g
 select new
 {
     AverageValue = g.Average(p => p.Value),
     CreationTimeStr = g.Key.time.Year + "-" + g.Key.time.Month + "-" + g.Key.time.Day+" "+g.Key.time.Hour+":00:00",
     MaxValue = g.Max(x => x.Value),
     MinValue = g.Min(x => x.Value)
 }).ToList();

其餘類推io

group by 半小時

group by 半小時=group by 30分鐘class

(from d in YourData.OrderBy(x => x.CreationTime)
 group d by new
 {
     time = new { d.CreationTime.Year, d.CreationTime.Month, d.CreationTime.Day,  d.CreationTime.Hour, Minute = (d.CreationTime.Minute / 30) * 30 }
 } into g
 select new
 {
     Value = g.Average(p => p.Value),
     CreationTimeStr = g.Key.time.Year + "-" + g.Key.time.Month + "-" + g.Key.time.Day + " " + g.Key.time.Hour + ":"+g.Key.time.Minute.ToString().PadRight(2,'0')+ ":00",
     MaxValue = g.Max(x => x.Value),
     MinValue = g.Min(x => x.Value)
 }).ToList();

group by 半月、半年等等能夠類比List

參考資料

Grouping by every n minutesselect

相關文章
相關標籤/搜索