我是在 相当 熟悉c#中的LINQ,但对我的foreach循环是否会造成过度枚举感到迷茫。
假设运行以下代码片段。
var listOfStuff = new List<CustomObject>
{
new CustomObject { Id = 1, Cost = 20M },
new CustomObject { Id = 2, Cost = 11M },
new CustomObject { Id = 3, Cost = 3.75M },
new CustomObject { Id = 4, Cost = 50.99M }
};
var newObjects = listOfStuff.Select(thing =>
new AnotherObject { Id = x.ID, NegaCost = decimal.Negate(x.Cost) });
foreach (var i in n) // a list of objects with a length of n
{
var match = newObjects.Where(PreDefinedPredicate);
i.DoSomethingWith(match);
}
是一个新 AnotherObject
是我误解了多次枚举的概念,还是实例被创建了N次?
这要看你怎么处理 match
在 i.DoSomethingWith
但如果你在那里迭代它,那么是的。
你可以随时检查你的假设,引入一些副作用,如 Console.WriteLine
:
var newObjects = listOfStuff.Select(x =>
{
Console.WriteLine($"Here with id: {x.Id}"); // SIDEEFFECT
return new AnotherObject { Id = x.ID, NegaCost = decimal.Negate(x.Cost) };
});
foreach (var i in n) // a list of objects with a length of n
{
var match = newObjects.Where(PreDefinedPredicate);
i.DoSomethingWith(match);
}