views:

50

answers:

2

I currently have many linq expressions nested within foreach loops ... kind of defeating the point of using linq!

What I'm trying to achieve is a simple blog model (blog posts which have multiple tags and are associated with multiple categories... that's all).

I'm looking for a way to condense all my linq expressions into a single expression, and the way I'm attempting to do it at the moment isn't returning desired results. Here's a basic representation of what I'm trying at the moment:

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.
}

I'm sure that its something simple that I'm missing here, but can't figure it out and thought that Stack Overflow would be able to answer this easily.

Thanks in advance!

A: 

I think this will do the trick:

var blogs = 
    from blog in db.BlogPosts
    select new
    {
        Blog = blog,
        Categories = blog.BlogCategories.ToArray(),
        Tags = blog.Junc_BlogTags.Select(bt => bt.Tag).ToArray()
    };

No more ugly joining. I hardly ever have to write a single join statement in LINQ.

Steven
That looks neat, but blog.BlogCategories doesn't exist in my database context. Not sure if I am able to create this either as I don't have access to the database schema.
Greg
@Greg: When that's the case perhaps I've misinterpreted your data model, but perhaps you haven't designed your .dbml (we're talking about LINQ to SQL right?) correctly. When you put the right relations between the entities in your designer, there is no need to use those awful `join` statements.
Steven
+1  A: 

It's not clear exactly what you'd prefer to get instead of what you're currently getting, but how about this?

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
            };
Daniel Renshaw
that was helpful, thanks
Greg