Stefan Kovacs
Stefan Kovacs

Reputation: 65

foreach iteration after Select

Can anyone explain this behaviour ?

class Program
{
    static void Main(string[] args)
    {
        var models = Enumerable.Range(0, 10).Select(x => new Model { Id = x.ToString() });

        foreach (var model in models)
        {
            model.Data = $"{model.Id} Data bla";
        }

        foreach (var model in models)
        {
            Console.WriteLine($"{model.Id} | {model.Data}");
        }

        Console.ReadLine();
    }
}

public class Model
{
    public string Id { get; set; }
    public string Data { get; set; }
}

Output :

0 |

1 |

2 |

However, if I call ToList() after the Select, my output changes to:

0 | 0 Data bla

1 | 1 Data bla

2 | 2 Data bla

I've tried putting a breakpoint in each of the foreach blocks and called

models.Any(x=>x.Equals(model))

but always returns false without the ToList() call

Upvotes: 2

Views: 249

Answers (1)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

models is a sequence that gets populated with new instances of Model each time you iterate over it. I.e. you get a new set of instances every time you foreach over it.

When you call ToList() you capture a copy of one of the iterations and all the instances which can then be modified.

Upvotes: 6

Related Questions