我想要显示输出所有月和所有的价格,但我想按组每月和总价每月例如:看看如何输出在照片中
[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 });
}
}
发布于 2018-07-28 12:25:57
下面的代码片段可能会有帮助:
注意: 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();
发布于 2018-07-29 01:29:11
好吧,如果你需要一些建议:
1-我建议把你的业务逻辑从控制器方法中去掉。尝试在名为SERVICES或BLL的新文件夹中创建一个新类,并从那里创建所有逻辑,然后在控制器方法中调用它。
2-使用Async task pattern创建方法,这样在某些任务完成之前,您的应用程序中就不会出现死锁。
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,会对你有很大的帮助
回答你的问题,遵循下面的例子: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);
}
https://stackoverflow.com/questions/51567840
复制相似问题