VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C# 根据天、周、月汇总统计生成统计报表

先看核心代码:

复制代码
     public List<DataEntity> SearchShopSalesReport(DateTimeOffset? dateFrom, DateTimeOffset? dateTo,string groupBy)   
     {          
            var query = data.DataEntity      //这里data为DbContext
                .AsEnumerable();

            if (dateFrom.HasValue)
                query = query.Where(x => x.Date >= dateFrom);
            if (dateTo.HasValue)
                query = query.Where(x => x.Date <= dateTo);
       
       //注意根据天分组统计
            var groupBy = DynamicQueryable.GroupBy<DataEntity, dynamic>(query.AsQueryable(), x => new { x.Date.Day });
       
       //注意根据周分组统计
      if (groupby.Equals("2")) 
        groupBy = DynamicQueryable.GroupBy<DataEntity, dynamic>(query.AsQueryable(), x => new { Week = x.Date.Date.GetWeekOfYear() }); 
      else if (groupby.Equals("3")) //注意根据月分组统计
        groupBy = DynamicQueryable.GroupBy<DataEntity, dynamic>(query.AsQueryable(), x => new { x.Date.Month }); 

      query = groupBy.Select(g => new DataEntity { 
        ShopId = g.FirstOrDefault().ShopId, 
        MarketplaceId = g.FirstOrDefault().MarketplaceId, 
        Date = g.FirstOrDefault().Date, 
        Sessions = g.Sum(x => x.Sessions), 
        BoxPercentage = g.Average(x => x.BuyBoxPercentage)
      }).ToObservableCollection(); 

    return query.ToList();
复制代码

 DynamicQueryable.GroupBy()与ToObservableCollection()还有GetWeekOfYear()方法

1
2
3
4
5
6
public static class DynamicQueryable
 {        public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>       
          (IQueryable<TSource> query, Expression<Func<TSource, TKey>> keySelector)
     {
           return query.GroupBy(keySelector);
     }<br>      <br>    

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> col)
{
return new ObservableCollection<T>(col);
}

1
<br>}<br><br>

public static class DateTimeExtension
{
public static int GetWeekOfYear(this DateTime dt)
{
GregorianCalendar calendar = new GregorianCalendar();
return calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);//注意这里一周是以星期一为第一天
}
}

1
<br>前端图表显示使用插件:echarts 官网为:<a href="https://www.echartsjs.com/zh/index.html">https://www.echartsjs.com/zh/index.html</a>


相关教程