[英]what is the most efficient way to identify and replace an object within an ObservableCollection?
I have a method that receives a customer object which has changed properties and I want to save it back into the main data store by replacing the old version of that object. 我有一个方法接收一个已更改属性的客户对象,我想通过替换该对象的旧版本将其保存回主数据存储。
Does anyone know the correct C# way to write the pseudo code to do this below? 有谁知道正确的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);
}
The most efficient would be to avoid LINQ ;-p 最有效的是避免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;
}
}
If you want to use LINQ: this isn't ideal, but would work at least: 如果你想使用LINQ:这不是理想的,但至少会起作用:
var oldCust = customers.FirstOrDefault(c => c.Id == customer.Id);
customers[customers.IndexOf(oldCust)] = customer;
It finds them by ID (using LINQ), then uses IndexOf
to get the position, and the indexer to update it. 它通过ID(使用LINQ)找到它们,然后使用IndexOf
获取位置,并使用索引器来更新它。 A bit more risky, but only one scan: 风险更大,但只有一次扫描:
int index = customers.TakeWhile(c => c.Id != customer.Id).Count();
customers[index] = customer;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.