Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Determine if List<T> is dirty?

I am serializing Lists of classes which are my data entities. I have a DataProvider that contains a List.

I always modify items directly within the collection.

What is the best way of determining if any items in the List have changed? I am using the Compact Framework.

My only current idea is to create a hash of the List (if that's possible) when I load the list. Then when I do a save I re-get the hash of the list and see if they're different values. If they're different I save and then update the stored Hash for comparison later, if they're the same then I don't save.

Any ideas?

like image 549
djdd87 Avatar asked Nov 29 '22 20:11

djdd87


1 Answers

If the items you add to the list implement the INotifyPropertyChanged interface, you could build your own generic list that hooks the event in that interface for all objects you add to the list, and unhooks the event when the items are removed from the list.

There's a BindingList<T> class in the framework you can use, or you can write your own.

Here's a sample add method, assuming the type has been declared with where T: INotifyPropertyChanged:

public void Add(T item)
{
    // null-check omitted for simplicity
    item.PropertyChanged += ItemPropertyChanged;
    _List.Add(item);
}

and the this[index] indexer property:

public T this[Int32 index]
{
    get { return _List[index]; }
    set {
        T oldItem = _List[index];
        _List[index] = value;
        if (oldItem != value)
        {
            if (oldItem != null)
                oldItem.PropertyChanged -= ItemPropertyChanged;
            if (value != null)
                value.PropertyChanged += ItemPropertyChanged;
        }
    }
}

If your items doesn't support INotifyPropertyChanged, but they're your classes, I would consider adding that support.

like image 88
Lasse V. Karlsen Avatar answered Dec 05 '22 23:12

Lasse V. Karlsen