【问题标题】:How to generate elements of IEnumerable One by One如何一一生成 IEnumerable 的元素
【发布时间】:2018-09-09 23:22:47
【问题描述】:

假设我有一个 IEnnumerable<Thing> enumerable 对象,并且此列表中的每个 Thing 生成起来都很昂贵。

当我去执行下面的代码时,当代码到达第 1 行时会有相当大的开销,因为据我了解,整个列表是在开始迭代之前生成的。

foreach(Thing t in enumerable)   // line 1
{                                // line 2
    DoStuffWith(t);              // line 3
}

有没有办法只根据需要生成每个Thing?像这样

while(enumerable.HasMoreThings())
{
    var e = enumerable.GenerateNextThing();
    DoStuffWith(e);
}

原码

using (var db = new PolyPrintEntities())
{
    var sw = new Stopwatch();
    sw.Start();
    IEnumerable<NotificationDto> notifications = db.EmailServiceNotifications
        .Select(not => new NotificationDto
        {
            Notification_ID = not.Notification_ID,
            StoredProcedure = not.StoredProcedure,
            SubjectLine = not.SubjectLine,
            BodyPreface = not.BodyPreface,
            Frequency = not.Frequency,
            TakesDateRange = not.TakesDateRange,
            DateRangeIntervalHours = not.DateRangeIntervalHours,
            TakesAssociateId = not.TakesAssociateId,
            NotificationType = not.NotificationType,
            Associates = not.SubscriptionEvent.SubscriptionSubscribers
                .Select(ss => new AssociateDto
                {
                    Record_Number = ss.Associate.Record_Number,
                    Name = ss.Associate.Name,
                    Email = ss.Associate.EMail
                })

        });
    sw.Stop();
    Console.WriteLine($"Enumeration:{sw.ElapsedMilliseconds}"); //about .5 seconds
    sw.Reset();

    sw.Start();
    //List is generated here, this is where lag happens. 
    int i = 0;
    foreach (var n in notifications)
    {
        if(i == 0)
        {
            sw.Stop();
            Console.WriteLine($"Generation:{sw.ElapsedMilliseconds}"); //about 10 seconds
            i++;
        }
        var ret = n.GetEmails();
        db.EmailQueues.AddRange(ret);
    }
    db.SaveChanges();
}

【问题讨论】:

  • "整个列表在开始迭代之前就在那里生成。"这正是IEnumerable/IEnumerable&lt;T&gt; 接口所避免的。你搞错了
  • 补充一下 Camilo 所说的,while (enumerable.MoveNext()) 是当你迭代一个可枚举的对象时发生的事情。我们需要查看更多您的代码 - 问题一定出在其他地方。 (什么是创建列表?你在使用yield吗?)
  • 枚举来自于一个 Linq 语句,该语句通过实体框架减小对数据库的查询大小。我对创建 IEnumerable 的代码块和只创建第一个对象的 foreach 循环部分进行了计时。我已经修改了我的帖子以包含导致我写这个问题的代码
  • 我们需要看到最重要的部分://List is generated here, this is where lag happens.
  • @maccettura 好的。对此感到抱歉,我不确定公约是什么。但现在我知道了,谢谢你的建议。

标签: c# .net linq deferred-execution


【解决方案1】:

只需yield他们。

while(enumerable.HasMoreThings()) 
{
    yield return enumerable.GenerateNextThing();
}

每次有人想要下一个项目(可能是这个函数的调用者)时,这个函数都会懒惰地创建和yield个项目。

【讨论】:

    【解决方案2】:

    Foreach 是一个 c# 语言结构,它变成了与您的第二个代码部分非常相似的东西。 IEnumerable 旨在完全按照您的意愿行事,它只会在您需要时一次提供 1 个项目

    【讨论】:

      【解决方案3】:

      我想通了。

      似乎在进一步完善 mycode 后,我获得了一些与我的想法不一致的经验数据。

      我使用 sw 以不同的方式测量时间:

              using (var db = new PolyPrintEntities())
              {
                  var sw = new Stopwatch();
                  sw.Start();
                  IEnumerable<NotificationDto> notifications = db.EmailServiceNotifications
                      .Select(not => new NotificationDto
                      {
                          Notification_ID = not.Notification_ID,
                          StoredProcedure = not.StoredProcedure,
                          SubjectLine = not.SubjectLine,
                          BodyPreface = not.BodyPreface,
                          Frequency = not.Frequency,
                          TakesDateRange = not.TakesDateRange,
                          DateRangeIntervalHours = not.DateRangeIntervalHours,
                          TakesAssociateId = not.TakesAssociateId,
                          NotificationType = not.NotificationType,
                          Associates = not.SubscriptionEvent.SubscriptionSubscribers
                              .Select(ss => new AssociateDto
                              {
                                  Record_Number = ss.Associate.Record_Number,
                                  Name = ss.Associate.Name,
                                  Email = ss.Associate.EMail
                              })
      
                      });
      
      
      
                  sw.Stop();
                  Console.WriteLine($"Enumeration:{sw.ElapsedMilliseconds}"); //about .5 seconds
                  sw.Reset();
                  sw.Start();
      
                  //Each item appears to be generated One by One 
                  int i = 0;
                  foreach (var n in notifications)
                  {
                      sw.Stop();
                      Console.WriteLine($"Generation_{i}:{sw.ElapsedMilliseconds}"); //about 1 second
                      var ret = n.GetEmails();
                      db.EmailQueues.AddRange(ret);
                      sw.Start();
                      i++;
                  }
                  db.SaveChanges();
              }
      

      和输出:

      Enumeration:404
      Generation_0:985
      Generation_1:986
      Generation_2:986
      

      看来,我认为我需要做的事情,其实我已经在做。

      我注意使从数据库返回的数据尽可能不统一,以避免获得错误的数据。

      【讨论】:

      • 是的,但是,我想保持堆栈溢出的精神。我只是认为这就是您回答自己问题的方式
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多