0

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");
        }
    }
liudger
  • 31
  • 7
  • maybe duplicate this https://stackoverflow.com/a/14237111/4588756 – Hossein Sep 20 '20 at 12:02
  • This question reveals a problem in your understanding of the difference between values and references Perhaps this could help [Value vs Reference types](http://www.albahari.com/valuevsreftypes.aspx) – Steve Sep 20 '20 at 12:08

2 Answers2

1

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)));
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

you try to compare the reference of two different objects. you must compere the contents of the two list. have a look at https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?view=netcore-3.1