C#/ LINQ的新手,在查询中分组不起作用

时间:2018-05-07 19:33:52

标签: c# linq

var query2 = from o in db.Orders join in db.Order_Details on o.OrderID equals od.OrderID                  将o.ShipCountry分组到oByCountry                  选择新的TotalPerCountry                  {                      Country = o.ShipCountry,                      总计= oByCountry.Sum(od.UnitPrice * od.Quantity)                  };

对于每个国家/地区,我需要显示该国家/地区的总金额。

如果查看图表,我将ShipCountry从Order表中取出。 要计算总金额,我将UnitPrice乘以数量。

我是LINQ的新手,所以我做错了。如何正确获得此查询?

另外,如何对query2的结果执行另一个查询? 是通过在'select new'后面添加一个名称,所以它给结果表这个名字吗?

diagram

修改

因此我们发现此查询为解决方案:

            var query2 = from o in db.Orders
                     join od in db.Order_Details on o.OrderID equals od.OrderID
                     group new { o, od } by o.ShipCountry into oByCountry
                     orderby oByCountry.Sum(ood => ood.od.UnitPrice * ood.od.Quantity) descending
                     select new
                     {
                         Country = oByCountry.Key,
                         Total = oByCountry.Sum(ood => ood.od.UnitPrice * ood.od.Quantity)
                     };

如何在另一个查询中使用此查询中的国家/地区? 我找到了下面的一个,但它在where子句中给出了一个错误。 (关于匿名类型的问题)如何以正确的方式执行该查询?

            var newquery = from c in db.Customers
                    join o in db.Orders on c.CustomerID equals o.CustomerID
                    join od in db.Order_Details on o.OrderID equals od.OrderID
                    where c.Country == query2.Country
                    group new {c, o, od} by c.CompanyName into cByName
                    orderby cByName.Sum(ood => ood.od.UnitPrice * ood.od.Quantity) descending
                    select new
                    {
                        cByName.Key,
                        Total = cByName.Sum(ood => ood.od.UnitPrice * ood.od.Quantity)
                    };

2 个答案:

答案 0 :(得分:0)

使用群组时,您需要访问Key,而不是Country = o.ShipCountry,使用Country = oByCountry.key,

var query2 = from o in db.Orders join od in db.Order_Details on o.OrderID equals od.OrderID
             group o by o.ShipCountry into oByCountry
             select new TotalPerCountry
             {
                 Country = oByCountry.key,
                 Total = oByCountry.Sum(od.UnitPrice * od.Quantity)
             };

答案 1 :(得分:0)

您的问题是,您正在对mov rax,0 (0x48C7C0xxxxxxxx takes 7 bytes) pushf + xor rax,rax + popf (0x9C31C09D takes 4 bytes). push 0 + pop rax (0x6A0058 takes 3 bytes) 而不是o进行分组,因此您无法访问od中的od。在分组中包含oByCountry

od

您可以在另一个查询中使用var query2 = from o in db.Orders join od in db.Order_Details on o.OrderID equals od.OrderID group new { o, od } by o.ShipCountry into oByCountry select new TotalPerCountry { Country = oByCountry.Key, Total = oByCountry.Sum(ood => ood.od.UnitPrice * ood.od.Quantity) }; ,只需引用它:

query2