2009-10-07 79 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