简体   繁体   English

在使用Group By子句重构LINQ语句时需要帮助吗?

[英]Need help refactoring a LINQ statement with a Group By clause?

The Linq-To-SQL that needs refactoring is found below: 在下面找到需要重构的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 };

with the following one-liner: 具有以下一线:

   group by p.ProductID

I know that group by omits any need for the select clause so both can live together in the same LINQ-To-SQL statement so can someone help me refactor the above please? 我知道group by省略了对select子句的任何需要,因此两者都可以一起生活在同一LINQ-To-SQL语句中,因此有人可以帮助我重构以上内容吗?

To help me remove any repeating data in my results. 为了帮助我删除结果中的所有重复数据。 <-- This is the entire point in this question. <-这是这个问题的重点。 A product is repeated a number of times based on the number of Flavours that are used by the product. 根据产品使用的调味剂的数量,将产品重复多次。 So as a result in the 'ShishaCombinations' table one ProductID may be repeated many times one for each flavour that it uses. 因此,在“ ShishaCombinations”表中,一个ProductID可能会针对其使用的每种口味重复多次。 I would like to group the results returned from the query above or call distinct on it as I don't want add the product 'n' times to my GUI because it appears 'n' number of times in my results. 我想对上述查询返回的结果进行分组,或对其进行调用,因为我不想将乘积“ n”次添加到我的GUI中,因为在结果中出现“ n”次。 Hopefully that will clear up any confusion of what I am trying to do. 希望这将消除对我正在尝试做的任何混淆。

The code below is all what I needed: 下面的代码就是我所需要的:

        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, thanks for answering mate. 乌福克,谢谢你答应伴侣 I knew my answer was a simple one lol : ) 我知道我的回答很简单:)

You can use into keyword after select clause. 您可以在select子句后使用into关键字。 You cannot just group by because you are projecting an anonymous type. 您不能仅按分组,因为您要投影匿名类型。

   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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM