【问题标题】:Need help refactoring a LINQ statement with a Group By clause?需要帮助使用 Group By 子句重构 LINQ 语句?
【发布时间】:2011-10-15 22:14:56
【问题描述】:

需要重构的Linq-To-SQL如下:

   var query = from p in Cache.Model.Products
               join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID
               where sc.NumberOfMixes ==  mixes
               select new { p.ProductID, p.Name };

使用以下单行:

   group by p.ProductID

我知道 group by 省略了对 select 子句的任何需求,因此两者可以一起存在于同一个 LINQ-To-SQL 语句中,所以有人可以帮我重构上述内容吗?

帮助我删除结果中的所有重复数据。

【问题讨论】:

  • 真的不清楚你所说的“To-SQL found below refactoring”是什么意思。鉴于您需要 NumberOfMixes 属性,您不能仅分组。
  • (如果你能展示你想要得到的结果,这可能有助于你的问题更清楚。)

标签: c# linq entity-framework .net-4.0 group-by


【解决方案1】:

下面的代码就是我所需要的:

        var query1 = (from p in Cache.Model.Products
                     join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID
                     where sc.NumberOfMixes == mixes
                     select new { p.ProductID, p.Name }).Distinct();

Ufuk,谢谢你的回答。我知道我的答案很简单,哈哈:)

【讨论】:

    【解决方案2】:

    您可以在 select 子句之后使用 into 关键字。你不能仅仅因为你在投射一个匿名类型而分组。

       var query = from p in Cache.Model.Products
                   join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID
                   where sc.NumberOfMixes ==  mixes
                   select new { p.ProductID, p.Name } into productInfo
                   group productInfo by productInfo.productId;
    

    【讨论】:

    • 似乎工作但没有乐趣?我完全理解您在回答中所说的话,但是即使没有 group by 子句,您的查询也会返回与我完全相同的结果? : S
    • @IbrarMumtaz 然后我猜您的 ProductID 列是唯一 ID,因此对该列进行分组没有任何作用。由于您不在 IGrouping 界面上使用元素,因此肯定是不必要的。你到底想做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多