简体   繁体   English

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

[英]what is the most efficient way to identify and replace an object within an ObservableCollection?

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

The most efficient would be to avoid LINQ ;-p 最有效的是避免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: 如果你想使用LINQ:这不是理想的,但至少会起作用:

    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. 它通过ID(使用LINQ)找到它们,然后使用IndexOf获取位置,并使用索引器来更新它。 A bit more risky, but only one scan: 风险更大,但只有一次扫描:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 更新ObservableCollection的最有效方法是什么? - How is the most efficient way to update an ObservableCollection? 排序 ObservableCollection 的最有效方法<T>里面有一个新项目 - Most efficient way of sorting ObservableCollection<T> with a new item in it 什么是将DataTable转换为对象的最有效方法[,]? - What's the most efficient way to convert a DataTable to an object[,]? 什么是从脚本中解析对象名称的最有效方法? - What can be the most efficient way to parse the object name from the script? 比较“对象”类型的值的最有效方法是什么 - What is the most efficient way to compare values of type “object” 替换xml流中文本的最有效方法 - Most efficient way to replace text in xml stream 在词典中添加到词典的最有效方法 - The most efficient way of Adding to a Dictionary within a Dictionary 管理大量数据(高度数据)并替换这个巨大数组的最有效方法是什么? - What's the most efficient way to manage large amounts of data (height data) and replace this huge array? 在 Azure 函数中将服务总线与 SQL Server 一起使用的最有效方法是什么? - What is the most efficient way of using service bus together with SQL Server within Azure functions? 执行此代码的最有效方法是什么? - What is the most efficient way to execute this code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM