ObservableCollection内のオブジェクトを識別および置換する最も効率的な方法は何ですか?

StackOverflow https://stackoverflow.com/questions/806548

  •  03-07-2019
  •  | 
  •  

質問

プロパティが変更された顧客オブジェクトを受け取るメソッドがあり、そのオブジェクトの古いバージョンを置き換えてメインデータストアに保存したい。

これを行うための擬似コードを記述するための正しい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 を使用して位置を取得し、インデクサーを使用して更新します。もう少し危険ですが、スキャンは1回だけです:

    int index = customers.TakeWhile(c => c.Id != customer.Id).Count();
    customers[index] = customer;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top