Linq SelectMany查询不工作
我有以下数据库表,其中主题和注释之间的关系为1:NLinq SelectMany查询不工作,linq,linq-to-sql,linq-to-entities,Linq,Linq To Sql,Linq To Entities,我有以下数据库表,其中主题和注释之间的关系为1:N Category id name Topic id title category_id Comment id details topic_id deleted (boolean) 我需要一个查询来计算每个类别中的评论总数。我有以下LINQ查询,但它不起作用: @foreach (var cat in Model.AllPermissionSets.Keys) { var commentCount = cat.Topics.Wh
Category
id
name
Topic
id
title
category_id
Comment
id
details
topic_id
deleted (boolean)
我需要一个查询来计算每个类别中的评论总数。我有以下LINQ查询,但它不起作用:
@foreach (var cat in Model.AllPermissionSets.Keys)
{
var commentCount = cat.Topics.Where(c => c.Comments.deleted != 0).SelectMany(x => x.Comments).Count();
@* some other stuff *@
}
在Visual studio中,我发现错误IList不包含已删除的定义…
执行上述操作的正确语法是什么?
Comments
是每个主题
实例上的集合类型属性。此集合没有已删除的属性。但是集合中的每个项目(注释的单个实例)都有它
这将为您提供该类别所有帖子中未删除评论的计数
第一部分,cat.Topics.Where(c=>c.Comments.Any(s=>!s.deleted))
将为您提供一个过滤后的Topic
集合列表,其中至少有一条未删除的注释。在第二部分中,您将选择所有这些帖子的评论
,并进行计数
抄袭自以下伊万·斯托夫的评论
下面的查询也将生成相同的结果,但更干净
var commentCount =cat.Topics.SelectMany(t => t.Comments.Where(c => !c.Deleted)).Count();
FWIW,这与SelectMany无关。问题出在Where子句中。在这种特定情况下,在SelectMany
中只包含一个Where
不是更好吗?如何避免存在子查询(任何部分)。我的意思是,类似于cat.Topics.SelectMany(t=>t.Comments.Where(c=>!c.Deleted)).Count()
Yes。这也会给你同样的结果。谢谢你,埃文。我最初的快速回答是解决他的语法错误。我在答案中添加了您的解决方案,并对其进行了适当的归因。谢谢我喜欢你的版本。
var commentCount =cat.Topics.SelectMany(t => t.Comments.Where(c => !c.Deleted)).Count();