需要帮助使用 Group By 子句重构 LINQ 语句吗?
需要重构的 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 语句中,所以有人可以帮忙吗请我重构上面的内容?
帮助我删除结果中的任何重复数据。 <-- 这就是这个问题的全部要点。根据产品使用的风味数量,产品会重复多次。因此,在“ShishaCombinations”表中,一个 ProductID 可能会针对其使用的每种口味重复多次。我想对上面的查询返回的结果进行分组,或者对其进行调用,因为我不想将产品“n”次添加到我的 GUI,因为它在我的结果中出现“n”次。希望这能消除对我正在尝试做的事情的任何困惑。
The Linq-To-SQL that needs refactoring is found below:
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?
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. 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. Hopefully that will clear up any confusion of what I am trying to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 select 子句之后使用 into 关键字。您不能仅仅分组,因为您正在投影匿名类型。
You can use into keyword after select clause. You cannot just group by because you are projecting an anonymous type.
下面的代码就是我所需要的:
Ufuk,感谢您的回答。我知道我的答案很简单,哈哈:)
The code below is all what I needed:
Ufuk, thanks for answering mate. I knew my answer was a simple one lol : )