首页 文章

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

提问于
浏览
0

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

对于每个国家,我需要显示该国家的总金额 .

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

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

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

diagram

EDIT:

所以我们发现这个查询作为解决方案:

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

    您的问题是您正在分组 o 而不是 od ,因此您无权访问 oByCountry 中的 od . 在分组中包含 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

    var TotalAs = from t in query2
                  where t.Country.StartsWith("A")
                  select t;
    
  • 0

    当你使用group by时,你需要访问 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)
                 };
    

相关问题