4

我有一个方法可以接收已更改属性的客户对象,我想通过替换该对象的旧版本将其保存回主数据存储中。

有谁知道在下面编写伪代码的正确 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);
    }
4

1 回答 1

3

有效的方法是避免 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;
于 2009-04-30T12:08:00.947 回答