Tuesday, November 16, 2010

.NET: IEnumerable is *not* lazy

Just spent ten minutes working this one out.

If you have a variable

IEnumerable<Foo> SomeFoos = [...LINQ expression returning an enumerable...];

and then do this

foreach (var foo in SomeFoos) { [...update foo...] }

you will almost certainly not see any changes in the values in SomeFoos.  Why not?  Because each time you iterate through SomeFoos, the enumerator is run again, quite possibly recreating each item.

A solution is to force each item in SomeFoos to be manifested once.  For example,

List<Foo> SomeFoos = [...LINQ expression returning an enumerable...].ToList();

Now things will work as expected.

[N.B.  When I say "laziness", I refer to the standard functional programming practice of replacing an evaluated thunk with the result, thereby avoiding any repeated processing effort on subsequent reads of the thunk.]

1 comment:

Mavor said...

Hello Rafe, this is Mavor from Stack overflow. I just wanted to express my gratitude for your help on my problem.

I'm just getting into C# and it was really helpful seeing you talk about actually using lambda.

I coulden't find an email addy for you.. so this is the best I can do to contact you. :)

If we could corrospond over email that would be great. I'm going to try implimenting my tree using the idea of lambdas and if I had someone to talk to it would be really nice. :)