【问题标题】:Difficulties generating a matrix table with LINQ使用 LINQ 生成矩阵表的困难
【发布时间】:2014-09-20 10:54:37
【问题描述】:

我正在尝试使用以下模型通过 LINQ 查询矩阵表:

public class Order
{
    public int Id { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
    public virtual ICollection<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public int Id { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public int OrderId { get; set; }
    public int ProductId { get; set; }
    public virtual Order Order { get; set; }
    public virtual Product Product { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public string Sku { get; set; }
    public decimal UnitPrice { get; set; }
    public virtual ICollection<OrderLine> OrderLines { get; set; }
}

我想要解决的问题:获取每月售出的产品数量。

到目前为止我的查询

var matrix = (from o in Context.Orders
                group o by o.DateCreated.Month
                into grp
                select new ReportingMatrix
                {
                    Month = grp.Key,
                    MatrixData = (from p in grp
                        from li in p.OrderLines
                        group li by li.ProductId
                        into lgr
                        select new ReportingMatrixData
                        {
                            ProductCode = (from pr in lgr
                                group pr by pr.Product.ProductName
                                into pgp
                                select pgp.Key).FirstOrDefault(),
                            Cases = lgr.Sum(l => l.Quantity)
                        }).ToList()
                }).ToList();

这“有点”有效,但我需要解决一些问题。

三月份我有 10 种产品。 4 月,我又创建了 2 个。 8 月再增加 3 个。

所以对于 1 月 - 3 月,我想查看我在 4 月和 8 月创建的产品,销售数量为 0。现在这些产品被排除在数据收集之外。

在我看来,这使得循环变得困难。我希望收集的数据能够反映所有产品,如果它们在 2 月份不存在,则只需显示 0。

我用来查询的 ViewModel:

public class ReportingMatrix
{
    public int Month { get; set; }
    public List<ReportingMatrixData> MatrixData { get; set; }
}

public class ReportingMatrixData
{
    public string ProductName { get; set; }
    public int Cases { get; set; }
}

问题

  1. 我需要对查询进行哪些更改才能执行我想要的操作 做?
  2. 如何循环数据以在我的 HTML 中创建表格?
  3. 我现在使用 int 表示月份,但我真的很想得到 字符串表示。无法完成这项工作。

【问题讨论】:

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


    【解决方案1】:

    我认为最好的方法不是尝试将其仅放在一个 Linq 查询中。

    只需创建单独的查询来选择不同的月份和产品,然后创建一个 linq 查询来汇总给定产品和月份的订单。允许 0 作为默认结果值。

    这也将更容易解决 2. 和 3. 附加提示,获取所有月份名称:

    someDateTime.Month.ToString("MMMM")
    

    或使用第一个代码 sn-p 来自: http://www.britishdeveloper.co.uk/2010/09/month-names-c-datetime-culture.html

    其他建议:研究其他连接类型,例如全连接、外连接

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2016-02-15
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多