我有一段代码返回如下所示的JSON结果:
return JsonConvert.SerializeObject(allData.OrderBy(x => x.DataDate.Value.Date)
.Select(item =>
new { Date = item.DataDate.Value.ToString("yyyy-MM-dd"),
Sales = (int)item.SalesForDay,
Revenue = (int?)item.RevenueForDay.Value }));
从上面可以看到,代码行返回HAD销售的所有日期...
例如,图表将具有:
10th of October - 3 Sales - Revenue 1100$
8th of October - 3 Sales - Revenue 1100$
4th of October - 3 Sales - Revenue 1100$
2nd of October - 3 Sales - Revenue 1100$
1st of October - 3 Sales - Revenue 1100$
返回的语句应将当前日期(10月12日)的所有日期返回到过去30天没有销售的日期,并在这些日期中放置0.00收入...
我该如何实现?
有人可以帮我吗?
答案 0 :(得分:1)
这是针对您的问题的定制解决方案。虽然我知道这不是最好的解决方案,但可以解决您的目的。
首先,创建一个DTO
public class SalesDataDTO
{
public DateTime Date { get; set; }
public int Sales { get; set; }
public int Revenue { get; set; }
}
第二,复制此实用程序功能
public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
最后调用此函数以获取所需的输出:
public List<SalesDataDTO> GetReportData()
{
// 1. Define date range
DateTime fromDate = DateTime.Now.Date;
DateTime toDate = DateTime.Now.Date.AddDays(-30);
// 2. create object to store final result
List<SalesDataDTO> saleDataList = new List<SalesDataDTO>();
// 3. create basic data
foreach (DateTime day in EachDay(fromDate, toDate))
{
saleDataList.Add(new SalesDataDTO { Date = day });
}
// 4. get actual data from db
List<SalesDataDTO> actualReportData = allData.OrderBy(x => x.DataDate.Value.Date)
.Select(item =>
new SalesDataDTO
{
Date = item.DataDate.Value.ToString("yyyy-MM-dd"),
Sales = (int)item.SalesForDay,
Revenue = (int?)item.RevenueForDay.Value
});
// 5. a bit customization
saleDataList.ForEach(record =>
{
var actualData = actualReportData.FirstOrDefault(x => x.Date.Date == record.Date.Date);
if (actualData != null)
{
record.Sales = actualData.Sales;
record.Revenue = actualData.Revenue;
}
});
// 6. return data
return saleDataList;
}
稍后您可以使用JsonConvert.SerializeObject(saleDataList);
进一步序列化数据。