When I add .ToList() at the end of the Select() statement it works as expected. What's the difference between IEnumerable and List in this case?
class Foo{
public string Name { get; set; }
public Guid Id { get; set; }
}
class Program
{
static void Main(string[] args)
{
var list = new List<string>(){ "first", "last" };
var bar = list.Select(x => new Foo {
Name = x,
Id = Guid.NewGuid()
}); //.ToList();
Console.WriteLine("bar Count = " + bar.Count());
Console.WriteLine();
for (int i = 0; i < 3; i++) {
Console.WriteLine(bar.First().Name + " " + bar.First().Id);
Console.WriteLine(bar.Last().Name + " " + bar.Last().Id);
Console.WriteLine();
}
}
}
Result:
examples Count = 2
first 1fabd003-340c-44a4-81ca-1908f206ccdb last 213f40c9-0705-4676-ad1f-73de21c5bc62
first 9bc117e5-1f10-4855-af95-46258b39955c last cd787227-12d9-4e25-88bc-634369d85671
first c787e081-8dd3-475c-bf24-44e5f103ed3a last 7a72080d-2dee-47b1-a55d-af0a7665d0ea
Result with .ToList()
bar Count = 2
first 3c1d4f1d-eecd-438a-86a4-e7db0680cad3 last cba1867d-d246-477e-b938-0f9cce457a5c
first 3c1d4f1d-eecd-438a-86a4-e7db0680cad3 last cba1867d-d246-477e-b938-0f9cce457a5c
first 3c1d4f1d-eecd-438a-86a4-e7db0680cad3 last cba1867d-d246-477e-b938-0f9cce457a5c