gpt4 book ai didi

c# - 如何逐一生成IEnumerable的元素

转载 作者:行者123 更新时间:2023-11-30 20:16:18 25 4
gpt4 key购买 nike

假设我有一个 IEnumerable<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();
}

最佳答案

简单yield他们。

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

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

关于c# - 如何逐一生成IEnumerable的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49582541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com