Search code examples
c#listcomparison

C# List comparison


This prints false. why is that and how can i make it so that it prints true? my goal is to have a list of people and a temp list of people that the user can edit. at the end of the users edit i want to check if the temp list is any different from the original list, so i can check if the program should bother saving the newly edited list.

static void EqualLists()
    {
        List<Person> listA = new List<Person>();
        List<Person> listB = new List<Person>();
        Person a = new Person()
        {
            name = "John",
            age = 18
        };
        Person b = new Person()
        {
            name = "John",
            age = 18
        };
        listA.Add(a);
        listB.Add(b);

        if(listA == listB)
        {
            Console.WriteLine("true");
        }
        else
        {
            Console.WriteLine("false");
        }
    }

Solution

  • First, we need to define what equality means. You clearly mean it as "the lists have the same semantic contents", but:

    • if(listA == listB) is a reference comparison, which means "are the same actual list instance"
    • this can be tweaked by using listA.SequenceEqual(listB), but this then needs to know what equality means per item
    • by default, this is going to use EqualityComparer<T>.Default, which for reference types, defaults to "things are equal if they are the same object instance"
    • to fix that you'd need to override GetHashCode() and Equals(object) correctly (and ideally also implement IEquatable<T>)

    A simpler approach might be:

    var same = listA.Select(p => (p.age, p.name)).SequenceEqual(
        listB.Select(p => (p.age, p.name)));