C# 获取近十周的每周一日期,然后通过sql查出来的按周分组进行匹配,没有则补0进行报表统计

通过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 in list)
            {
                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;
    }

 

posted @ 2020-07-16 09:33  吴政恒  阅读(478)  评论(0编辑  收藏  举报