Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update property in object collection with linq

Tags:

c#

linq

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();
like image 577
Maxim Avatar asked Aug 15 '13 20:08

Maxim


3 Answers

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.

like image 58
Jon Avatar answered Oct 18 '22 17:10

Jon


The code works - after executing schedule.ForEach() the Name property is updated. Maybe there is something that you've left out.

like image 45
Slugart Avatar answered Oct 18 '22 18:10

Slugart


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.

like image 26
Tim Schmelter Avatar answered Oct 18 '22 18:10

Tim Schmelter