【问题标题】:How can i get Max Date in Linq我如何在 Linq 中获得最大日期
【发布时间】:2020-11-19 17:08:49
【问题描述】:

我有以下 linq 表达式将用户参数与 Max(EndDate) 字段进行比较?。我有多个 EndDate,但我想得到最后一个。

这里是 产品1

 EndDate

2018-09-30 23:59:59.000
2019-09-30 23:59:59.000

产品 2

 EndDate


2019-09-30 23:59:59.000
2019-12-31 23:59:59.000

当用户输入 09/2019 时,我只需要返回产品 1,因为 Max(EndDate) == 用户输入的值是 09/2009,格式为 MM/yyyy,目前它同时显示产品 1 和产品 2 .

在我的模型中,我将 checkBillingMonth 作为布尔值

public bool checkBillingMonth { get; set; }

这里我的 linq 表达式看起来像这样,但它同时返回 prodcut 1 和 product 2

var billingProductList = Context.Product.AsNoTracking()
        .Select(p => new ProductDTO 
         {
          checkBillingMonth = p.Billing
          .Any(b => b.EndDate.Month == request.FromDate.Month &&
               b.EndDate.Year == request.FromDate.Year)
         }).ToList();

如何修改上述 linq 表达式以获取 Max(EndDate) 并与 request.FromDate 进行比较?

【问题讨论】:

  • 您将 Linq-to-Entities 与 Linq-to-Objects 混合使用 - 这可能会给您带来次优查询,可能会将整个表加载到内存中。
  • 此外,您发布的代码语法无效 - 您缺少大括号和点。
  • ProductDTO 代表什么? (为什么它有一个名为checkBillingMonth 的属性?这是一个很奇怪的领域模型……)

标签: c# asp.net asp.net-mvc linq


【解决方案1】:

你可以试试下面的代码。

    var billingProductList = Context.Product.AsNoTracking()
            .Select(p => new ProductDTO 
             {
              checkBillingMonth = GetCheckBillingMonth(p.Invoices, request.FromDate) 
        // I'm not sure why you were having the condition related to min date
             }).ToList();

私有方法:

 private bool GetCheckBillingMonth(List<Invoice> invoices, DateTime fromDate)
 {
     if (invoices == null || invoices.Count == 0) return false;

     var latestInvoiceEndDate = invoices.OrderByDescending(x => x.EndDate).FirstOrDefault()?.EndDate;        
     return latestInvoiceEndDate != null && latestInvoiceEndDate.Month == fromDate.Month && latestInvoiceEndDate.Year == fromDate.Year;        
 }

【讨论】:

  • 是的,创建一个私有函数并将这段代码移到其中。现在您可以调用该函数来确定所需的值。我希望我已经回答了你的问题。如果您需要任何其他详细信息,请告诉我
  • @mjwills,将代码修改为只调用一次 OrderByDescending。
【解决方案2】:

如果我正确理解了这个问题,您想与上一张发票进行比较吗?然后,您应该将主要结果集从 Product 翻转到 Invoice。过滤最新的发票。然后选择相关的产品详情。

Context.Invoice
   .AsNoTracking()
   .Where(i => i.EndDate == i.Product.Invoices.Max(i2 => i2.EndDate))
   .Select(i => new ProductDTO{
      checkBillingMonth = i.EndDate.Month == request.FromDate.Month &&
               i.EndDate.Year == request.FromDate.Year && 
               !request.FromDate.Equals(DateTime.MinValue)),
      // plus other properties from i.Product
   });
;

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 2012-05-16
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多