先看核心代碼: public List<DataEntity> SearchShopSalesReport(DateTimeOffset? dateFrom, DateTimeOffset? dateTo,string groupBy) { var query = data.DataEntity / ...
先看核心代碼:
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