Getting rid of nested foreach loops when using linq

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)
{
    // 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 clear this code!

+3
source share
4 answers

, .

List<Blog> blogs = 
(
  from t in tag
  where t.Name == tagName
  from tj in t.Junc_Tag_Blogs
  let b = tj.Blog
  select b
).ToList();
+4
var blogsWithGivenTag =
    from blog in db.BlogPosts
    where blog.BlogTags.Any(bt => bt.Tag.Name == tagName)
    select blog;
+1
0

You can put blogs into the dictionary, group the sites in the blog id and scroll through the groups:

var blogDict = blogs.ToDictionary(b => b.Id);

foreach(var group in tagJunk.GroupBy(j => j.Fk_Blog_Id)) {
  if (blogDict.ContainsKey(group.Key)) {
    var blog = blogDict[group.Key];
    foreach (var junction in group) {
      // here you have the blog and the junction
    }
  }
}

These are also nested loops, but for each blog you are simply projecting the nodes that actually belong to this blog, and not all connections.

0
source

Source: https://habr.com/ru/post/1762435/


All Articles