我对C#和LINQ非常陌生,现在我需要对一个又一个嵌套的导航表进行一些汇总,生成结果如下:
[{
"ForumMain":"General Forum",
"Forums": [{
"Title":"My First Forum",
"TopicCount":4,
"PostCount":[2,0,1,0]
},
{
"Title":"My Second Forum",
"TopicCount":0,
"PostCount":[]
}]
}]
我希望
PostCount
也是总和,但是当我尝试对PostCount
求和时却给出了调试null错误,请参见下面的linq查询:var data = ForumCategories.Select(f => new
{
ForumMain = f.CategoryName,
Forums = f.Fora.Select(t => new
{
Title = t.ForumName,
TopicCount = t.Topics.Count,
PostCount = t.Topics
.Select(m => m.ForumPosts.Count == null ? 0 : m.ForumPosts.Count)
})
});
最佳答案
据我了解,您希望在PostCount
下拥有该Forum
中所有主题的职位总数。对?
如果是这样的话:
var data = db.ForumCategories.Select(f => new
{
ForumMain = f.CategoryName,
Forums = f.Fora.Select(t => new
{
Title = t.ForumName,
TopicCount = t.Topics.Count,
PostCount = t.Topics.SelectMany(x => x.ForumPosts).Count()
})
});