gpt4 book ai didi

c# - 在C#中产生两个列表项的集合差异

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:04 25 4
gpt4 key购买 nike

我有 2 个可用列表。我需要收集不再使用的数据。

例如

列表 1:

  • 1
  • 2
  • 3
  • 4
  • 5

list 2:

  • 1
  • 2
  • 4
  • 5
  • 6

结果数据集需要。

列表 2 中未包含的项目:

  • 3

我希望使用类似以下内容的东西:

var itemsNotInList2 = List2.Except(List1).ToList();

最佳答案

您正在处理 List<int>在此示例中,您的想法是正确的,只是 args 颠倒了。应该是;

var itemsNotInList2 = List1.Except(List2).ToList();

想想如何用通俗易懂的英语表达这一点。获取itemsNotInList2我想把所有东西都放在List1除了 List2 中的内容.您在问题中的代码为您提供了 List2 中的项目但不在List1List2以来就没有了是 List1 的子集

请注意,这种方法通常不适合引用类型,因为默认的 comaparer 将比较引用本身。为了对对象进行类似的操作,您必须实现 IEqualityComparer并调用接受它作为第三个参数的重载。例如,如果您正在处理 List<Person>Person有一个public string Ssid你可以定义 Equalreturn p1.Ssid == p2.Ssid并将其用作比较的基础。如果需要,您可以在 msdn 上找到这方面的示例。

public class Person
{
public string Ssid;
// other properties and methods
}

public class PersonSsidEqualityComparer : IEqualityComparer<Person>
{
public bool Equal(Person lhs, Person rhs)
{
return lhs.Ssid == rhs.Ssid
}

public int GetHashCode(Person p)
{
return p.Value.GetHashCode();
}
}

现在作为例子;

  List<Person> people = new List<Person>();
List<Person> otherPeople = new List<Person>();
Person p1 = new Person("123"); // pretend this constructor takes an ssid
Person p2 = new Person("123");
Person p3 = new Person("124");
Person p4 = p1;

现在一些使用我上面设置的数据的例子;

  people.Add(p1);
people.Add(p3);
otherPeople.Add(p2);

var ThemPeople = people.Except(otherPeople);
// gives you p1 and p3

var ThemOtherPeople = people.Except(otherPeople, new PersonSsidEqualityComparar());
// only gives you p3

otherPeople.Add(p4);
var DoingReferenceComparesNow = people.Except(otherPeople);
// gives you only p3 cause p1 == p4 (they're the same address)

关于c# - 在C#中产生两个列表项的集合差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399009/

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