简体   繁体   English

如何添加查询LINQ从表中获取结果?

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

I want to display output all month and all price but I want by group month and sum price each month ex:look how output in photo 我想显示所有月份和所有价格的输出,但是我想按组月份和每个月的总价显示:查看照片的输出方式 在此处输入图片说明

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

Below code snippets may be helpful: 以下代码段可能会有所帮助:

NOTE: tbl51567840 - it is a table having same data as per your snip 注意: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();

Well, if you want some piece of advice: 好吧,如果您需要一些建议:

1 - I would suggest taking your Business Logic out of the controller methods. 1-我建议您从控制器方法中删除业务逻辑。 Try to make a new class, in a new folder named SERVICES or BLL and make all the logic from there then calling it within your controller methods. 尝试在名为SERVICES或BLL的新文件夹中创建一个新类,并从那里进行所有逻辑,然后在控制器方法中调用它。
2- Make the method using the Async Task pattern so you wont see deadlocks in your app until the finished of some task. 2-使用“异步任务”模式制作方法,以便在完成某些任务之前,您不会在应用程序中看到死锁。
3- Use in your controller classes the ActionResult return method instead of JSonResult so you get used with it when you have different returns within your method. 3-在控制器类中使用ActionResult返回方法而不是JSonResult,以便在方法中有不同的返回值时使用它。

example 2 and 3: 示例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- Reference to Newtonsoft.json, look it at NuGet, would help you a lot with the JSON 4-参考Newtonsoft.json,在NuGet上查看它,它将对JSON有很大帮助

Anwsering your question, follow the bellow example from: Linq get sum of data group by date 回答您的问题,请遵循以下示例: 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