views:

119

answers:

1

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);
    }
+3  A: 

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
I used your second version and it worked, excellent, thanks.
Edward Tanguay