Home > Enterprise >  What is the best way to check if a list of object has changed?
What is the best way to check if a list of object has changed?

Time:06-30

I have a form with options. If any property value of the options change, I have to do another action.

What is the best way to check if the list of Option have changed? The Class Option is very nested, so it is hard to check it with a foreach.

I thought to save at the beginning the hashCode of the List. And compare the hashCode at the end.

List<Option> optionLit = GetOptionList();

CodePudding user response:

A quick an easy way to do this would be to serialise the list at the beginning (of any operations) and then serialise the list after you operations are complete and compare the two strings.

You can serialise the list like this:

List<Option> optionList = GetOptionList();
string jsonString = JsonSerializer.Serialize(optionList);

Note: you will need to include the System.Text.Json namespace to use the JsonSerializer class: using System.Text.Json;

CodePudding user response:

Upvoted for DiplomacyNotWar and YungDeiza solutions and here mine (just in case):

Create this class:

public abstract class NotifyPropertyChangeBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Then inherite it in your class:

public class MyMainObject: NotifyPropertyChangeBase
{
    public bool HasChanged { get; set; }
    public MyNestedObject1 Nested1
    {
        get { return nested1; }
        set
        {
            this.nested1= value;
            this.HasChanged = true;
            NotifyPropertyChanged();
        }
    }
    public MyNestedObject2 Nested2
    {
        get { return nested2; }
        set
        {
            this.nested2= value;
            this.HasChanged = true;
            NotifyPropertyChanged();
        }
    }

    private MyNestedObject1 nested1;
    private MyNestedObject2 nested2;
}

If needed, use the "NotifyPropertyChangeBase" in nested classes also. In your GUI, bind some object/event to "HasChanged" property and you should be notified when object changed.

  • Related