简体   繁体   中英

How to get changes from an array or a collection

i have some values (i can put them in an array or a collection) like

original = "1", "2", "3", "4", "5, "6", "7", "8", "9"

The user can do changes on this items. The user can delete some or add new ones:

modified = "2", "3", "4", "6", "10", "11"

The user has added "10" and "11" in this sample and deleted "1", "5", "7", "8" and "9".

How can i get these changes from my array or collection. I need a resultset of deleted items with "1", "5", "8", "9" and another one of added items "10" and "11". How can i get these changes?

You can use the Except extension method:

var added = modified.Except(original);    // "10", "11"
var removed = original.Except(modified);  // "1", "5", "7", "8", "9" 

But you might want to look at using an ObservableCollection<T> instead in case you need to react to the modifications as they happen.

You can use an ObservableCollection<T> instead and subscribe to its CollectionChanged event. There are Add and Remove actions (among others) that are passed to you in the event handler and you can take a decision based on that.

var original = new ObservableCollection<string> { "1", "2", "3", "4", "5, "6", "7", "8", "9" };

original.CollectionChanged += (s, e) => {
  if(e.Action == NotifyCollectionChangedAction.Add) {
    //Store or do something with added items in e.NewItems.
  } 
  else if (e.Action == NotifyCollectionChangedAction.Remove {
    //store or do something with removed items in e.OldItems
  }
};

original.Add("15");
original.RemoveAt(3);

The advantage over the other solution is that in case you're dealing with large collections you're not wasting memory on holding the original as well. You can work with only one collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM