gpt4 book ai didi

c# - 获取两个列表之间的差异

转载 作者:行者123 更新时间:2023-11-30 14:36:14 26 4
gpt4 key购买 nike

我有两个列表(ListAListB),这些列表的类型都是相同的PersonInfoLogin字段是唯一键。

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; }
}

我想比较这两个列表:

  1. 我想获取 ListA 中的项目列表,但在 ListB

    中不可用>
  2. 对于两个列表中可用的项目,我想从 ListA(Login 字段是唯一键)中获取项目的列表是两个列表之间的差异。

示例:如果 ListA 中的 Login "MyLogin",FirstName 的值与 中的值不匹配列表BLogin 为“MyLogin”的项目必须是结果列表的一部分。

示例:如果特定登录的 ListAListB 之间的 Age 不同,则该项目必须是结果的一部分

谢谢。

最佳答案

要比较自定义数据类型列表的对象,您需要在您的类中实现IEquatable 并覆盖GetHashCode()

检查这个MSDN Link

你的类(class)

    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);
}
}

然后这里是你如何使用它(如 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));

关于c# - 获取两个列表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com