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

有谁知道正确的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);
    }
有帮助吗?

解决方案

最有效的将避免使用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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top