簡體   English   中英

如何添加查詢LINQ從表中獲取結果?

[英]How can add Query LINQ to get result from table?

我想顯示所有月份和所有價格的輸出,但是我想按組月份和每個月的總價顯示:查看照片的輸出方式 在此處輸入圖片說明

[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 });
        }
    }

以下代碼段可能會有所幫助:

注意: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-我建議您從控制器方法中刪除業務邏輯。 嘗試在名為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按日期獲取數據組的總和

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM