我想显示所有月份和所有价格的输出,但是我想按组月份显示
和每个月的总价,例如:看看照片的输出结果
[HttpGet("api/recent-reports")]
public JsonResult GetStatusSummaryRecentReports()
{
try
{
IEnumerable<Booking> list = _bookingDataService
.Query(d => d.BookingDate.Month < (DateTime.Now.Month));
IEnumerable<int> data_month = list.Select(d => d.BookingDate.Month)
.Distinct().Take(4);
StatusSummaryRecentReports obj = new StatusSummaryRecentReports();
//obj.Total_Order_ByMonth = Total_PriceOreder_Each_Month;
//obj.Months = Months;
return Json(obj);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { message = ex.Message });
}
}
答案 0 :(得分:0)
下面的代码段可能会有所帮助:
注意:tbl51567840-该表的数据与您的代码段相同
//Solution:1 - step by step
//Step 1.1 > Create iQueryable view to get desired fields to make it virutal/logical table!
//It is inline query and it is not executed here until you call ToList at below. So it is just like SQL CTE
var query1 = (from i in db.tbl51567840
select new { Month = i.BookingDate.Value.Month, Price = i.Price.Value });
//Step 1.2 > Apply conditions and other logic to get desired result
var result = (from l in query1
where l.Month < DateTime.Now.Month
group l by l.Month into g
select new { Month = g.Key, Total = g.Sum(s => s.Price) }).ToList();
//Solution:2 Result in one linq query
var query2 = (from i in db.tbl51567840
where i.BookingDate.Value.Month < DateTime.Now.Month
group i by i.BookingDate.Value.Month into g
select new { Month = g.Key, Total = g.Sum(s => s.Price) }).ToList();
答案 1 :(得分:0)
好吧,如果您需要一些建议:
1-我建议您将业务逻辑从控制器方法中删除。尝试在名为SERVICES或BLL的新文件夹中创建一个新类,并从那里进行所有逻辑,然后在您的控制器方法中调用它。
2-使用“异步任务”模式制作该方法,以便在完成某些任务之前,您不会在应用程序中看到死锁。
3-在控制器类中使用ActionResult返回方法而不是JSonResult,以便在方法中有不同的返回值时使用它。
示例2和3:
[HttpGet("api/recent-reports")]
public async Task<ActionResult> GetStatusSummaryRecentReports()
{
// When you call your class that has your Business logic, make it as async task pattern as well, so you will call it using the await keyword such as:
// MyBusinessLogicClass resultFromBll = new MyBusinessLogicClass();
// var getResult = await resultFromBll.MethodGroupByMonthAndSum();
...your controller code here...
}
4-对Newtonsoft.json的引用,请查看NuGet,它将对JSON有很大帮助
回答您的问题,请遵循以下示例:Linq get sum of data group by date
static void Main()
{
var list = new List<meter_reading>
{
new meter_reading {Date = new DateTime(2000, 2, 15), T1 = 2, T2 = 3},
new meter_reading {Date = new DateTime(2000, 2, 10), T1 = 4, T2 = 5},
new meter_reading {Date = new DateTime(2000, 3, 15), T1 = 2, T2 = 3},
new meter_reading {Date = new DateTime(2000, 3, 15), T1 = 5, T2 = 4}
};
var sum = list
.GroupBy(x => GetFirstDayInMonth(x.Date))
.Select(item => new meter_reading
{
Date = item.Key,
T1 = item.Sum(x => x.T1),
T2 = item.Sum(x => x.T2),
}).ToList();
}
private static DateTime GetFirstDayInMonth(DateTime dateTime)
{
return new DateTime(dateTime.Date.Year, dateTime.Date.Month, 1);
}