我是否在枚举我的IEnumerable<T> n次?

问题描述 投票:0回答:1

我是在 相当 熟悉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次?

c# linq enumeration deferred-execution
1个回答
3
投票

这要看你怎么处理 matchi.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);
}
© www.soinside.com 2019 - 2024. All rights reserved.