【问题标题】:Getting rid of nested foreach loops when using linq使用 linq 时摆脱嵌套的 foreach 循环
【发布时间】:2011-04-06 04:57:46
【问题描述】:

我总是发现自己在创建仍然大量使用嵌套 foreach 循环的 linq 表达式。下面是我所说的一个简单示例,如果这里有人能告诉我如何将这种低效率的代码压缩成单个 linq 表达式,我将非常感激?

数据库上下文(db)有三个表:Blog、Tag、Junc_Tag_Blog。联结表只是存储带有标签的博客记录。

不管怎样,这是我乱七八糟的代码:

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

提前感谢能帮我清理这段代码的人!

【问题讨论】:

    标签: c# linq linq-to-sql optimization foreach


    【解决方案1】:

    您可以构造一个查询,让数据库为您找到匹配项。

    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();
    

    【讨论】:

      【解决方案2】:
      var blogsWithGivenTag =
          from blog in db.BlogPosts
          where blog.BlogTags.Any(bt => bt.Tag.Name == tagName)
          select blog;
      

      【讨论】:

        【解决方案3】:

        【讨论】:

          【解决方案4】:

          您可以将博客放入字典中,对博客 ID 上的连接进行分组,然后循环遍历这些组:

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

          这也是嵌套循环,但对于每个博客,您只循环通过实际属于该博客的联结,而不是所有联结。

          【讨论】:

            猜你喜欢
            • 2020-08-04
            • 1970-01-01
            • 2014-02-12
            • 1970-01-01
            • 2023-03-17
            • 2020-02-21
            • 1970-01-01
            • 2011-06-07
            相关资源
            最近更新 更多