I have already read answers in questions Update object in IEnumerable<> not updating? and Updating an item property within IEnumerable but the property doesn't stay set? but I would like to Understand why it is not working when I try to update an item in an IEnumerable.
What I don't understand is:
I cannot update an item of an Ienumerable using .ElementAt() method when the source collection is pointing to an Ienumerable.
However the same code works when the source Ienumerable is pointing to a list.
1 Could someone be kind to explain what happens behind the scenes?
2 Why C# compiler doesn't (or can't) error on this?
3 Also doesn't this invalidate using Ienumerable to define types when we have to convert Ienumerables to Lists whenever it needs updating?
I am sure I am missing something here I'd appriciate if someone can explain what's going on behind the scenes.
This is my code:
1 - Collection doesn't get updated:
class Person
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var numbers = new int[] {1,2,3};
var people = numbers.Select(n => new Person { Name = "Person " + n.ToString() });
for (int i = 0; i < people.Count(); i++)
{
people.ElementAt(i).Name = "New Name";
}
people.ToList().ForEach(i => Console.WriteLine(i.Name));
// OUTPUT: Person1, Person2, Person3
}
}
2 - Collection gets updated when I add .ToList() to the collection creation line (Note 3rd line in the Main method)
class Person
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var numbers = new int[] {1,2,3};
// Note the .ToList() at the end of this line.
var people = numbers.Select(n => new Person { Name = "Person " + n.ToString() }).ToList();
for (int i = 0; i < people.Count(); i++)
{
people.ElementAt(i).Name = "New Name";
}
people.ToList().ForEach(i => Console.WriteLine(i.Name));
Console.ReadLine();
// OUTPUT: New Name, New Name, New Name
}
}