4

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);
    }
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • Thanks for asking this question. I asked something similar earlier this week (http://stackoverflow.com/questions/800091/how-do-i-update-an-existing-element-of-an-observablecollection) but not as well as you just did. – Scott Lawrence Apr 30 '09 at 13:35

1 Answers1

3

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;
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900