![](/img/trans.png)
[英]How is the most efficient way to update an ObservableCollection?
[英]what is the most efficient way to identify and replace an object within an 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);
}
最有效的是避免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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.