what is the most efficient way to identify and replace an object within an ObservableCollection?
-
03-07-2019 - |
Question
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?
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);
}
Solution
The most efficient would be to avoid 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:
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. A bit more risky, but only one scan:
int index = customers.TakeWhile(c => c.Id != customer.Id).Count();
customers[index] = customer;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow