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();
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.
The code works - after executing schedule.ForEach() the Name property is updated. Maybe there is something that you've left out.
LINQ is not the right tool to modify collections, it is a tool to query collections. If you want to modify it you need a loop, for example a foreach
:
var schedule = data.Select(d => new Schedule{ ID = d.id }).ToList();
foreach(var s in schedule)
s.Name = "Condition Name";
If you want to "modify" a collection with LINQ you have to create a new one and assign that to your variable which is inefficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With