-1

I have 2 lists of objects, and I need to know if any property has changed. Here is what I have:

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

Then, I have 2 lists of Person.

var list1 = new List<Person>();
var list2 = new List<Person>();

I need to know if list1 and list2 contains some Person objects, make sure that the values ​​of the properties are the same, comparing through the PersonId.

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Mati Silver
  • 185
  • 1
  • 13
  • 1
    Have you tried anything? Have you looked into linq? This [`joins`](http://stackoverflow.com/documentation/c%23/68/linq-queries/2994/joins-inner-left-right-cross-and-full-outer-joins#t=201611241921121673108) documentation is a good place to start. Also just using a `where` can do – Gilad Green Nov 24 '16 at 19:20
  • Yes, my question is referred to compare all properties at same time – Mati Silver Nov 24 '16 at 19:29
  • 1
    So yet again please show what you have tried... We can help you correct it but not write it for you – Gilad Green Nov 24 '16 at 19:30
  • Possible duplicate of [IEqualityComparer and Contains method](http://stackoverflow.com/questions/14580595/iequalitycomparer-and-contains-method) – Massimiliano Kraus Nov 24 '16 at 20:30

1 Answers1

0

I'm sure there are different ways to do this but my suggested solution is below.

var list1 = new List<Person>
{
    new Person()
    {
        PersonId = 123,
        Name = "Tom",
        Email = "tom@x.com"
    }
};


var list2 = new List<Person>
{
    new Person()
    {
        PersonId = 123,
        Name = "Tom",
        Email = "tom@x.com"
    }
};

var count = list1.Count;
if(list1.Count.Equals(list2.Count))
{
    var i;
    for(i=0; i< list1.Count; i++)
    {
        if(!list1[i].PersonId.Equals(list2[i]))
        {
            //DO somthing they lists are NOT SAME
            //One of the Person object contain different ID
        }
    }
}
else
{
    //DO somthing, list count is different..
}

I would also recommend trying using

Dictionary<string, Person> 

Key value pairs where the string would be Person's ID and have two Dictionary key compared to see if it exist in the other Dictionary, it does not iterate through the whole Dictionary which makes it less heavier

Hope it helps

Luminous_Dev
  • 614
  • 6
  • 14