代码之家  ›  专栏  ›  技术社区  ›  Greg

将linq表达式压缩为一个简单blog系统的表达式

  •  1
  • Greg  · 技术社区  · 14 年前

    我现在有很多linq表达式嵌套在foreach循环中。。。有点挫败了使用linq的意义!

    我试图实现的是一个简单的博客模型(博客文章有多个标签,并与多个类别。。。仅此而已)。

    var blogs = 
        from blog in db.BlogPosts
        join categories in db.BlogCategories
            on blog.Fk_Category_Id equals category.Id
        // Using a junction table because blogs can have multiple tags,
        // and tags can be shared across different blogs.
        join juncTags in db.Junc_BlogTags
            on blog.Id equals juncTags.Fk_BlogPost_Id
        join tags in db.Tags
            on juncTags.FK_Tag_Id equals tags.Id
        select new
        {
            blog,
            categories,
            tags
        };
    
    foreach(var blog in blogs)
    {
        blog.blog // Correct, can obtain information of current blog...
        blog.categories // Correct, shows the information of Blog's category
        blog.tags // Wrong, only refers to the first tag - next itteration will 
        // show the same blog with the next tag .. not what I want.
    }
    

    我确信我在这里遗漏了一些简单的东西,但是我无法理解,并且认为堆栈溢出能够很容易地回答这个问题。

    提前谢谢!

    1 回复  |  直到 14 年前
        1
  •  1
  •   Daniel Renshaw    14 年前

    var blogs = from blog in db.BlogPosts
                join categories in db.BlogCategories
                    on blog.Fk_Category_Id equals category.Id
                select new
                {
                    blog,
                    categories,
                    tags = from juncTags in db.Junc_BlogTags
                           join tags in db.Tags
                               on juncTags.FK_Tag_Id equals tags.Id
                           where juncTags.Fk_BlogPost_Id = blog.Id
                           select tags
                };