gpt4 book ai didi

c# - 如何在 C# 中有效地比较两个大型对象列表的属性?

转载 作者:行者123 更新时间:2023-11-30 20:16:54 25 4
gpt4 key购买 nike

我有一个包含两个对象列表的数据集,它的 ID 在两个列表中都是一致的,但其他属性可能不同也可能不同。我怎样才能最有效地检索基于一个或多个属性的不同属性?

我通常的做法与此类似。我的对象设置如下:

   public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }

public bool IsEqual(Person other)
{
if (Name != other.Name)
{
return false;
}
if (Age != other.Age)
{
return false;
}
return true;
}
}

IsEqual 比较器用于将其与某个等效对象进行比较。

然后我找到修改过的人的方法是这样的:

  public static List<Person> FindModifiedPeople(List<Person> listA, List<Person> listB)
{
var modifiedPeople = new List<Person>();
foreach (var personA in listA)
{
var matchingPerson = listB.FirstOrDefault(e => e.ID == personA.ID);
if (matchingPerson == null)
{
continue;
}

if (!personA.IsEqual(matchingPerson))
{
modifiedPeople.Add(personA);
}
}
return modifiedPeople;
}

在我的数据集中,我不关心 listB 中但不在 listA 中的人,因此我不需要遍历这两个列表。我只需要检查 listA 中的 listB 中的元素(可能存在也可能不存在)并返回已修改的人员列表(使用 listA 中的元素)。

这种方法适用于相当小的名单,但现在我有两个大约有 160,000 人的名单,这种方法需要几分钟时间。有什么方法可以使此方法更有效,同时仍返回我需要它做的事情吗?

最佳答案

如果您可以将列表更改为 Dictionary<int, Person>以此人的 ID 作为 key ,他们将对您有用。这将在 O(n) 中运行而不是你的 O(n^2) .

public static List<Person> FindModifiedPeople(Dictionary<int, Person> dictA, Dictionary<int, Person> dictB)
{
var modifiedPeople = new List<Person>();
foreach (var personA in dictA)
{
Person matchingPerson;
if(dictB.TryGetValue(personA.Key, out matchingPerson))
{
if (!personA.Value.IsEqual(matchingPerson))
{
modifiedPeople.Add(personA.Value);
}
}
}
return modifiedPeople;
}

您还可以根据需要将返回类型从 List 更改为另一个 Dictionary。

编辑

正如@maccettura 在他的评论中指出的那样,您确实应该覆盖内置的 equals 方法。这将使您的代码看起来像这样。

public override bool Equals(Object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;

var otherPerson = (Person)obj;

if (Name != otherPerson.Name)
{
return false;
}
if (Age != otherPerson.Age)
{
return false;
}
return true;
}

这将允许您的代码处理任何期望使用默认 Equals 方法而不是自定义方法的东西。

关于c# - 如何在 C# 中有效地比较两个大型对象列表的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47558257/

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