【问题标题】:Is this the correct way to use LINQ Group By?这是使用 LINQ Group By 的正确方法吗?
【发布时间】:2013-10-29 00:17:50
【问题描述】:

我有两张桌子。汽车和经销商。每辆车都有一个与之关联的dealerID。每个经销商都有一个状态属性。我需要编写一个查询,告诉我数据库中每个州有多少辆汽车。我还没有使用 group by 但我认为这就是它的用途。这是我在意识到我需要帮助之前所得到的。

        var query = (from c in _db.Cars
                     join d in _db.Dealers on c.DealerID equals d.DealerID
                     where c.Active == true
                     group c by d.State);

目标是列出每个州的列表视图,其中每个州的汽车总数作为最终结果。

【问题讨论】:

  • 您的查询正常吗?看起来它有效。 State的类型是什么?
  • 在一个简单的数据集上尝试一下,您可以轻松检查它是否返回正确的结果。
  • @KingKing 我无法选择状态并从中返回汽车数量。据我所知。

标签: c# sql linq tsql linq-to-sql


【解决方案1】:

让我帮忙用扩展方法写吧:

var query = 
_db.Cars
.Join
(
    _db.Dealers,
    c=>c.DealerID,
    d=>d.DealerID,
    (car,dealer)=>new {car,dealer}
)
.Where
(
    x=>x.car.Active//no reason to check with == true if this is boolean
)
.GroupBy
(
    x=>x.dealer.State
)
.Select
(
    x=>new 
    {
        State = x.Key,
        Cars = x.Count()
    }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2018-12-31
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多