识别和替换 ObservableCollection 中的对象的最有效方法是什么?

发布于 2024-07-17 14:23:35 字数 391 浏览 8 评论 0原文

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

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

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);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

皓月长歌 2024-07-24 14:23:35

最有效是避免 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),然后使用 < code>IndexOf 获取位置,索引器更新它。 风险更大一点,但只需扫描一次:

    int index = customers.TakeWhile(c => c.Id != customer.Id).Count();
    customers[index] = customer;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文