I always find that I create linq expressions that make heavy use of foreach nested loops. Below is a simple example of what I'm talking about, and I would really appreciate it if someone here showed me how to condense this low-performance code into a single linq expression?
The database context (db) has three tables: Blog, Tag, Junc_Tag_Blog. The conversion table simply stores a blog entry with their tags.
Anyway, here is my dirty code:
public static Collection<Blog> GetByTag(string tagName)
{
var tag = (from t in db.Tags
where t.Name == tagName
select t).Single();
var tagJunc = from tj in db.Junc_Tag_Blogs
where tj.Fk_Tag_Id == tag.Id
select tj;
var blogs = from b in db.BlogPosts
select b;
foreach(var blog in blogs)
{
foreach(var junc in tagJunc)
{
if(blog.Id == junc.Fk_Blog_Id)
{
}
}
}
}
Thanks in advance to the person who can help me clear this code!
source
share