我有一个方法接收一个已更改属性的客户对象,我想通过替换该对象的旧版本将其保存回主数据存储.
有谁知道正确的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;