Get the differences between 2 lists

前端 未结 5 458
你的背包
你的背包 2020-12-10 20:36

I have two lists (ListA and ListB), the type of these lists is the same PersonInfo, the Loginfield is a unique key.

5条回答
  •  不知归路
    2020-12-10 21:27

    To compare objects of custom data type lists, you will need to implement IEquatable in your class and override GetHashCode()

    Check this MSDN Link

    Your class

        public class PersonInfo : IEquatable
        {
            public string Login { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int Age { get; set; }
            public bool Active { get; set; }
    
            public bool Equals(PersonInfo other)
            {
                //Check whether the compared object is null.
                if (Object.ReferenceEquals(other, null)) return false;
    
                //Check whether the compared object references the same data.
                if (Object.ReferenceEquals(this, other)) return true;
    
                //Check whether the properties are equal.
                return Login.Equals(other.Login) && FirstName.Equals(other.FirstName) && LastName.Equals(other.LastName) && Age.Equals(other.Age) && Active.Equals(other.Active);
            }
    
            public override int GetHashCode()
            {
    
                int hashLogin = Login == null ? 0 : Login.GetHashCode();
    
                int hashFirstName = FirstName == null ? 0 : FirstName.GetHashCode();
    
                int hashLastName = LastName == null ? 0 : LastName.GetHashCode();
    
                int hashAge = Age.GetHashCode();
    
                int hashActive = Active.GetHashCode();
    
                //Calculate the hash code.
                return (hashLogin + hashFirstName + hashLastName) ^ (hashAge + hashActive);
            }
        }
    

    Then here is how you use it (as listed in Pranay's response)

                List ListA = new List() { new PersonInfo { Login = "1", FirstName = "James", LastName = "Watson", Active = true, Age = 21 }, new PersonInfo { Login = "2", FirstName = "Jane", LastName = "Morrison", Active = true, Age = 25 }, new PersonInfo { Login = "3", FirstName = "Kim", LastName = "John", Active = false, Age = 33 } };
                List ListB = new List() { new PersonInfo { Login = "1", FirstName = "James2222", LastName = "Watson", Active = true, Age = 21 }, new PersonInfo { Login = "3", FirstName = "Kim", LastName = "John", Active = false, Age = 33 } };
    
                //Get Items in ListA that are not in ListB
                List FilteredListA = ListA.Except(ListB).ToList();
    
                //To get the difference between ListA and FilteredListA (items from FilteredListA will be removed from ListA)
                ListA.RemoveAll(a => FilteredListA.Contains(a));
    

提交回复
热议问题