C# Update a List from Another List

后端 未结 5 1394
别跟我提以往
别跟我提以往 2020-12-16 12:50

I have 2 List. The first one, lets call it ListA is more like a complete list and the second one ListB is a modified list. Now what I want to do i
5条回答
  •  Happy的楠姐
    2020-12-16 13:18

    You could also use the Union method with an IEqualityComparer:

    var newList = ListB.Union(ListA, new PersonEqualityComparer());
    
    class PersonEqualityComparer : IEqualityComparer
    {
        public bool Equals(Person person1, Person person2)
        {
            if (person1 == null && person2 == null)
                return true;
            else if ((person1 != null && person2 == null) ||
                    (person1 == null && person2 != null))
                return false;
    
            return person1.Id.Equals(person2.Id);
        }
    
        public int GetHashCode(Person item)
        {
            return item.Id.GetHashCode();
        }
    }
    

提交回复
热议问题