C# 獲取近十週的每週一日期,然後通過sql查出來的按周分組進行匹配,沒有則補0進行報表統計
阿新 • • 發佈:2020-07-16
通過sql按周統計詳見https://www.cnblogs.com/ZhengHengWU/p/13305104.html
//資料庫通過sql查出按周分組的統計資料 List<Statistics> dbList = new List<Statistics>(); //獲取近十週的日期列表 DateTime dt = DateTime.Now; DateTime startWeek1 = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d"))); //本週週一 var newDt = startWeek1.AddDays(-(9 * 7)); List<Statistics> list = new List<Statistics>(); list.Add(new Statistics { CreateDate = newDt.ToString("yyyy-MM-dd") }); for (int i = 1; i < 9; i++) { newDt= newDt.AddDays(7); list.Add(new Statistics { CreateDate = newDt.ToString("yyyy-MM-dd") }); } list.Add(new Statistics { CreateDate = startWeek1.ToString("yyyy-MM-dd") }); //通過遍歷近十週的日期進行和資料庫查出來的資料進行比較,本週有值取count,沒值本週預設count為0 foreach (var item inlist) { item.Count = dbList.Where(t => t.CreateDate == item.CreateDate)?.FirstOrDefault()?.Count ?? 0; }
實體類:
public class Statistics { public string CreateDate { get; set; } public int Count { get; set; } = 0; }