【问题标题】:How can add Query LINQ to get result from table?如何添加查询 LINQ 以从表中获取结果?
【发布时间】:2018-07-28 03:44:41
【问题描述】:

我想显示整个月的输出和所有价格,但我想按组月 和每个月的总价格例如:看看照片中的输出

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

【问题讨论】:

  • 什么是_bookingDataService?
  • 私有 IDataService _bookingDataService;
  • 公共接口 IDataService { IEnumerable GetAll();无效创建(T实体); T GetSingle(Expression> 谓词); IEnumerable 查询(表达式> 谓词);无效更新(T实体);无效删除(T实体); }
  • 如果你有不同年份的同一个月怎么办?
  • 同月必须同年,

标签: c# asp.net-mvc linq


【解决方案1】:

下面的代码 sn-ps 可能会有所帮助:

注意: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();

【讨论】:

  • 如果有人想改进答案,请参考这个包含来自txt.do/dzneg的架构+数据的sql文件
  • 这个解决方案不能帮助它复杂的 sql 我想要 LINQ 新版本
  • LINQ 新版本?哪一个?
  • for ex:List list = new List { new Student{ StudentId=1, Name="Alan", Dob=new DateTime(2000,2,1) }, new Student{ StudentId=2, Name="Joe", Dob=new DateTime(1999,2,10) } }; //2 - 显示年龄最大的学生 DateTime min = list.Min(s => s.Dob); IEnumerable query2 = list.Where(s => s.Dob == min); //3 - 只显示三个字母的学生姓名 IEnumerable query3 = list.Where(s => s.Name.Length == 3);
  • IEnumerable query3 = list.Where(s => s.Name.Length == 3);
【解决方案2】:

好吧,如果你想要一些建议:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2019-01-02
    相关资源
    最近更新 更多