2009-10-07 117 views
1

如何使用LINQ从第二个列表中的对象更新一个列表中的对象?我的问题与LINQ In Line Property Update During Join非常相似,只是在我的情况下,第二个列表比父列表小。 换句话说,我想更新第二个集合中具有相应更新的主集合中的那些成员。否则,我希望主对象保持不变。上面引用的文章中的技术似乎导致两个集合的内部连接。加入收藏LINQ更新

感谢

回答

2

其他文章中的答案是罚款的问题太多,因为你真正想要的是内连接。重要的是要注意,内部连接只用于执行该功能,它不会修改列表(即,不符合内部连接的项目在列表中保持不变)。

为了完整这里的解决方案,我会用:

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); 

这里的输出我得到:

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