I'm working on comparing two versions of a listview, for a settings form. I need to know if the user actually modified the list at all, in which case when they click "Save" I'll actually save. If they didn't change anything, when they click "Save" I won't be wasting memory/time re-saving something they didn't change.
Anyway, how can I compare two ObservableCollections to see if they are at all different?
Thanks in advance!
You can use the LINQ Except method: Produces the set difference of two sequences.
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx
Consider the following sample method...
public void ExceptFunctioni()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);
if(aOnlyNumbers.Count()>0)
{
// do something
}
}
The Except method is invoked on the first collection and passed the second collection as an argument. The result will contain the differences. You can then query the result and take action accordingly. If both sequences are equal, the result's count will be zero.
Having said that, it's worthy to note that the preferred strategy in the MVVM world would be to use this method to control whether or not your 'Save' button is enabled. In this approach, if the two collections are equal, the 'Save' button would be disabled and the user could not access it.
But either way, the LINQ method offers a very condensed way of achieving what you're after...
ADDING: seeing the comments you made in reply to 'Dumb's' comment, your 'oldList' would correspond to numbersB in the sample code above...
Also the comment from 'Stonetip' (to whom thanks)...
More succinct: if(numbersA.Except(numbersB).Any()) { // do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With