C# – Update property in object collection with linq

clinq

Have a list of objects with the object structure as following

public class Schedule
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Schedule() {}
}

Executing a linq query on data I can see properly populated list of objects

var schedule = (from d in data 
                select new Schedule
                {
                    ID = d.id,
                    Name = "" 
                }).ToList();

later in code I want to change property Name depends on a condition. A few examples I found

schedule.ForEach(s => { s.Name = "Condition Name"; });
schedule.Select(s => { s.Name = "Condition name"; return s; });

after execution leave Name parameter "null" when I refresh schedule in the watch window.
Can anyone see what's wrong with this?

Looping through collection and trying to change Property doesn't change it either

   foreach (var sch in schedule)
   {
       sch.Name = "New name";
   }

schedule.ToList()[0].Name == ""

UPDATE

.ToList() call in the snippet below is important to make code work.

var schedule = (from d in data 
                select new Schedule
                {
                    ID = d.id,
                    Name = "" 
                }).ToList();

Best Answer

Your LINQ query that assigns a value to schedule creates independent objects based on the original collection (it effectively clones the objects); changing the properties of the clones does not change the original objects.