2009-10-07 3 views
1

LINQ를 사용하여 두 번째 목록의 개체에서 한 목록의 개체를 어떻게 업데이트합니까? 제 질문은 LINQ In Line Property Update During Join과 매우 흡사합니다. 제 경우에는 두 번째 목록이 상위 목록보다 작습니다. 즉, 두 번째 컬렉션에서 해당 업데이트가있는 마스터 컬렉션의 멤버를 업데이트하려고합니다. 그렇지 않으면 마스터 오브젝트가 변경되지 않은 상태로 유지되기를 원합니다. 위에서 언급 한 기사의 기술은 두 컬렉션의 내부 조인을 초래하는 것으로 보입니다. 당신이 정말로 원하는 것은 내부와 같이 다른 문서의 대답은 너무 당신의 문제에 대한 괜찮조인 된 컬렉션에서 LINQ 업데이트

감사

답변

2

은 가입 할 수 있습니다. 내부 조인은 함수를 수행하는 데만 사용되며 목록을 수정하지는 않습니다 (즉, 내부 조인을 충족하지 않는 항목은 목록에서 그대로 유지됩니다).

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 
: 여기
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); 

내가 얻을 출력입니다 : 완성도를 들어

여기 내가 사용하는 것이 해결책이다