Observe list items when hole list changes?

feronferon Member ✭✭

Let’s say I have a list of people. I reload the data by replacing the hole list with the new data. Is there a way to figure out if anything changed without comparing every single item like done below?

Right now I’m loading the data and redrawing everything again so the data is not outdated, but that’s probably using a lot more battery than necessary. It would be a lot nicer to only redraw if something changed.

class PersonPageViewModel
{
    List<Person> people = API.GetAllPeople();

    public void Refresh()
    {
        var refreshedPeople = API.GetAllPeople()


        for (int i = 0; i < refreshedPeople.Count; i++)
        {
            people[i].Name = refreshedPeople[i].Name;
        }
    }
}



class Person
{

    private string name;
    public string Name
    {

        get { return name; }

        set
        {
            if (name == value) return;
            name = value;
            NotifyPropertyChanged(“Name”);

        }

    }
}

Best Answer

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    I reload the data by replacing the hole list with the new data.

    If you want to replace the hole list, just assign the value of 'refreshedPeople' to 'people'. Refer to the code.

    class PersonPageViewModel
    {
        List<Person> people = API.GetAllPeople();
    
        public void Refresh()
        {
            people = API.GetAllPeople();
        }
    }
    
  • feronferon Member ✭✭

    @FlorianKriegl said:
    If you override Equals and GetHashCode in "Person" you could use "Except"

    var list3 = list1.Except(list2).ToList();
    

    so list3 will hold all the items that are in list2 but not in list1.

    That works nicely, thanks!
    I assume I can't use data binding in any way to figure out when a single item has changed, because the whole list is now a new list and the single items don't get modified but replaced instead?

  • FlorianKrieglFlorianKriegl ATMember ✭✭✭

    If you just want to add items thta have changed I would do the follwing:

    1. Uses ObservalbleList instead of List
    2. Inside the Refresh function get the items that differs from the current Collection (using except)
    3. Only add the new items to your collection and modify updated items (you have to use some sort of id to check if a item is new or if it has modified)
    4. Bind to the ObservableList

    This should do what you want to achive.

  • FlorianKrieglFlorianKriegl ATMember ✭✭✭

    Sorry, I meant, of course, ObservableCollection, not ObservableList.

  • feronferon Member ✭✭

    @FlorianKriegl Thanks!

Sign In or Register to comment.