views:

77

answers:

1

How do I use LINQ to update objects in one list from objects in a second list? My question is very similar to http://stackoverflow.com/questions/709560/linq-in-line-property-update-during-join except that, in my case, the second list is smaller than the parent list. In other words, I want to update those members of the master collection that have corresponding updates in a second collection. Otherwise I want the master object left unaltered. The technique in the article referenced above seems to result in an inner join of the two collections.

Thanks

+1  A: 

The answer in the other article is fine for your problem too, as what you really want is an inner join. It's important to note that the inner join is only used to perform the function, it's not modifying the list (i.e. items that don't meet the inner join are left untouched in the list).

For completeness here's the solution I would use:

List<Person> people = new List<Person>();
people.Add( new Person{ Name = "Timothy", Rating = 2 } );
people.Add( new Person{ Name = "Joe", Rating = 3 } );
people.Add( new Person{ Name = "Dave", Rating = 4 } );

List<Person> updatedPeople = new List<Person>();
updatedPeople.Add( new Person { Name = "Timothy", Rating = 1 } );
updatedPeople.Add( new Person { Name = "Dave", Rating = 2 } );

ShowPeople( "Full list (before changes)", people );

Func<Person, Person, Person> updateRating =
    ( personToUpdate, personWithChanges ) =>
    {
        personToUpdate.Rating = personWithChanges.Rating;
        return personToUpdate;
    };
var updates = from p in people
              join up in updatedPeople
                  on p.Name equals up.Name
              select updateRating( p, up );

var appliedChanges = updates.ToList();

ShowPeople( "Full list (after changes)", people );
ShowPeople( "People that were edited", updatedPeople );
ShowPeople( "Changes applied", appliedChanges );

Here's the output I get:

Full list (before changes)
-----
Name: Timothy, Rating: 2
Name: Joe, Rating: 3
Name: Dave, Rating: 4

Full list (after changes)
-----
Name: Timothy, Rating: 1
Name: Joe, Rating: 3
Name: Dave, Rating: 2

People that were edited
-----
Name: Timothy, Rating: 1
Name: Dave, Rating: 2

Changes applied
-----
Name: Timothy, Rating: 1
Name: Dave, Rating: 2
Timothy Walters