我有两个列表(ListA和ListB),这些列表的类型相同PersonInfo,Login字段是唯一键。
public class PersonInfo
{
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; }
}
Run Code Online (Sandbox Code Playgroud)
我想比较这两个列表:
我想得到一个ListA不可用的项目列表ListB
对于两个列表中可用的项目,我想从ListA(Login字段是唯一键)获取两个列表之间存在差异的项目的列表。
示例:如果对于中的Login“MyLogin” ListA, 的值FirstName与 中的值不匹配ListB。带有“MyLogin”的项目Login必须是结果列表的一部分。
示例:如果特定登录Age之间的ListA和ListB不同,则该项目必须是结果的一部分
谢谢。
要比较自定义数据类型列表的对象,您需要IEquatable在您的类中实现并覆盖GetHashCode()
检查此MSDN 链接
你的班
public class PersonInfo : IEquatable<PersonInfo>
{
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);
}
}
Run Code Online (Sandbox Code Playgroud)
那么这就是你如何使用它(如 Pranay 的回复中所列)
List<PersonInfo> ListA = new List<PersonInfo>() { 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<PersonInfo> ListB = new List<PersonInfo>() { 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<PersonInfo> 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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21015 次 |
| 最近记录: |