What is the most efficient way to identify and replace an object in an ObservableCollection?

I have a method that receives a client object that has changed properties, and I want to save it back to the main data store, replacing the old version of this object.

Does anyone know the correct C # way to write 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); } 
+4
source share
1 answer

The most effective 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 is not ideal, but will work at least:

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

He finds them by identifier (using LINQ), then uses IndexOf to get the position, and the indexer updates it. A bit more risky, but only one scan:

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

All Articles