【问题标题】:what is the most efficient way to identify and replace an object within an ObservableCollection?在 ObservableCollection 中识别和替换对象的最有效方法是什么?
【发布时间】:2009-04-30 11:59:24
【问题描述】:

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

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

【问题讨论】:

标签: c# wpf observablecollection


【解决方案1】:

最有效的是避免使用 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多