C# 根据天周月汇总统计生成统计报表
Posted gonghui2016
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()方法
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); }
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> col)
{
return new ObservableCollection<T>(col);
}
}
public static class DateTimeExtension
{
public static int GetWeekOfYear(this DateTime dt)
{
GregorianCalendar calendar = new GregorianCalendar();
return calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);//注意这里一周是以星期一为第一天
}
}
前端图表显示使用插件:echarts 官网为:https://www.echartsjs.com/zh/index.html
以上是关于C# 根据天周月汇总统计生成统计报表的主要内容,如果未能解决你的问题,请参考以下文章