I am always finding myself creating linq expressions that still use nested foreach loops heavily. Below is a simple example of what I'm talking about, and I'd really appreciate it if someone on here can show me how to condense this low-efficiency code into a single linq expression?
The database context (db) has three tables: Blog, Tag, Junc_Tag_Blog. The junction table simply stores a record of blogs with their tags.
Anyway, here's my messy code:
public static Collection<Blog> GetByTag(string tagName)
{
// Get the tag record.
var tag = (from t in db.Tags
where t.Name == tagName
select t).Single();
// Get the list of all junction table records.
var tagJunc = from tj in db.Junc_Tag_Blogs
where tj.Fk_Tag_Id == tag.Id
select tj;
// Get a list of all blogs.
var blogs = from b in db.BlogPosts
select b;
// Work out if each blog is associated with given tag.
foreach(var blog in blogs)
{
foreach(var junc in tagJunc)
{
if(blog.Id == junc.Fk_Blog_Id)
{
// We have a match! - do something with this result.
}
}
}
}
Thanks in advance to the person who can help me clean this code up!