需要帮助使用Groupby并在MVC的查询语句中一起加入

时间:2015-12-28 21:08:22

标签: sql asp.net-mvc-4 lambda

我有两个模型:部门和发票。

public partial class Invoice
{
    public int Id { get; set; }
    public int VendorId { get; set; }
    public int DepartmentID { get; set; }
    public string ItemName { get; set; }
    public decimal Price { get; set; }
    public DateTime Date { get; set; }
}

public partial class Department
{  
    public int Id { get; set; }
    public string Departments { get; set; }

    public virtual ICollection<Invoice> Invoices { get; set; }
}

我正在尝试按部门分组并列出每个部门的总价格。我可能几乎在那里,但倾向于完全失去所以任何帮助将不胜感激。

例如:

  • Foo - $ 135
  • 酒吧 - 450美元

我现在拥有的东西,但我迷失了陈述的选择部分:

var deptGroup = content.Departments
            .Join(content.Invoices, d => d.Id, i => i.DepartmentID, (d, i) => new { Department = d, Invoice = i })
            .GroupBy(d => d.Department.Departments)
            .OrderBy(d => d.Key); 

1 个答案:

答案 0 :(得分:0)

您几乎就在那里,您只需要为每个组选择发票价格的总和:

var deptGroup = content.Departments
        .Join(content.Invoices, d => d.Id, i => i.DepartmentID, (d, i) => new { Department = d, Invoice = i })
        .GroupBy(d => d.Department.Departments)
        .OrderBy(d => d.Key)
        .Select(d => new
        {
            DepartmentName = d.Key,
            TotalPrice = d.Sum(i => i.Price)
        };

值得注意的是,您不应该为此使用自己的联接和分组,因为每个部门已经有一组发票:

var deptGroup = content.Departments
        .Select(d => new
        {
            DepartmentName = d.Departments,
            TotalPrice = d.Invoices.Sum(i => i.Price)
        })
        .OrderBy(d => d.DepartmentName);