2009-04-30 2 views
4

속성을 변경 한 고객 개체를받는 메서드가 있는데 그 개체의 이전 버전을 바꾸어 주 데이터 저장소에 다시 저장하려고합니다.ObservableCollection 내에서 개체를 식별하고 바꿀 수있는 가장 효율적인 방법은 무엇입니까?

아래 코드를 작성하기 위해 올바른 C# 방식을 알고있는 사람이 있습니까?

public static void Save(Customer customer) 
    { 
     ObservableCollection<Customer> customers = Customer.GetAll(); 

     //pseudo code: 
     var newCustomers = from c in customers 
      where c.Id = customer.Id 
      Replace(customer); 
    } 
+0

고마워. 이번 주 초 비슷한 비슷한 질문을했지만 (http://stackoverflow.com/questions/800091/how-do-i-update-an-existing-element-of-an-observablecollection) 방금 전에했던 것처럼하지 않았습니다. –

답변

3

피해야하는 것입니다 가장 효율적인 LINQ ;-p

int count = customers.Count, id = customer.Id; 
    for (int i = 0; i < count; i++) { 
     if (customers[i].Id == id) { 
      customers[i] = customer; 
      break; 
     } 
    } 

당신은 LINQ를 사용하려면

:이 좋지 않은, 그러나 적어도 작동합니다 :

var oldCust = customers.FirstOrDefault(c => c.Id == customer.Id); 
    customers[customers.IndexOf(oldCust)] = customer; 

ID로 (LINQ를 사용하여) 찾은 다음 IndexOf을 사용하여 위치를 가져오고 인덱서가이를 업데이트합니다. 조금 더 위험하지만 단 하나의 스캔 :

int index = customers.TakeWhile(c => c.Id != customer.Id).Count(); 
    customers[index] = customer; 
+0

두 번째 버전을 사용했는데 정말 훌륭했습니다. –

관련 문제