我对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()
    })
});

10-06 12:16