Linq to Entry Join,Group,Sum with Northwind订单

时间:2018-07-17 13:33:28

标签: c# linq linqpad

我正在尝试编写一个linq查询,该查询应该对Northwind.mdb中的order_detail行进行求和,然后返回汇总的总计以及负责员工的一些详细信息。我正在使用LINQpad对其进行测试,这就是我到目前为止所拥有的

void Main()
{
    var result = (from e in Employees
        join o in Orders on e.EmployeeID equals o.EmployeeID
        join d in OrderDetails on o.OrderID equals d.OrderID
        where o.OrderID == 10250
        group new { e, o, d } by new 
        {
             o.OrderID, e.Address, e.BirthDate, e.City, e.Country,
             e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.HireDate,
             e.Region, e.PostalCode, e.HomePhone,
             e.Extension, e.ReportsTo,e.PhotoPath, e.EmployeeID,
             d.Quantity, d.UnitPrice, d.Discount
        }
        into grp select new   
        {
            Name = grp.Key.FirstName + " " + grp.Key.LastName,
            OrderID = grp.Key.OrderID,      
            Address = grp.Key.Address,
            SalesTotal = grp.Sum(x => x.d.UnitPrice * x.d.Quantity)
        });

        result.Dump();       
}

Output from LINQPad

我只希望一行,总计1813.00。有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

您没有在正确的级别分组。如果将其更改为按员工分组,则应该得到正确的结果:

void Main()
{
    var result = (from e in Employees
        join o in Orders on e.EmployeeID equals o.EmployeeID
        join d in OrderDetails on o.OrderID equals d.OrderID
        where o.OrderID == 10250
        group new { e, o, d } by new 
        {
             e.EmployeeID, e.FirstName, e.LastName, e.Address
        }
        into grp select new   
        {
            Name = grp.Key.FirstName + " " + grp.Key.LastName,
            Address = grp.Key.Address,
            SalesTotal = grp.Sum(x => x.d.UnitPrice * x.d.Quantity)
        });

        result.Dump();       
}

如果每个订单需要一行,也可以按该行分组:

void Main()
{
    var result = (from e in Employees
        join o in Orders on e.EmployeeID equals o.EmployeeID
        join d in OrderDetails on o.OrderID equals d.OrderID
        where o.OrderID == 10250
        group new { e, o, d } by new 
        {
             e.EmployeeID, e.FirstName, e.LastName, e.Address,
             o.OrderID
        }
        into grp select new   
        {
            Name = grp.Key.FirstName + " " + grp.Key.LastName,
            OrderID = grp.Key.OrderID,
            Address = grp.Key.Address,
            SalesTotal = grp.Sum(x => x.d.UnitPrice * x.d.Quantity)
        });

        result.Dump();       
}