先看核心代码:
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