c# - 检查两个 List<T> 是否相等的最快方法

标签 c# .net

我有两个列表

ListA<Emp>ListB<Emp> 两者都有 1000 条记录。

Emp是Employee类的一个对象。下面是我的Employee

public class Employee
{
    int ID = 0;
    string Name = String.Empty;
    string Dept = String.Empty;
    string Address = String.Empty;
    int Age = 0;
    string Email = String.Empty;
}

我想验证两个列表是否相等。 Emp 对象可以按不同的顺序放置。此外,可能有多个 Emp 对象在两个列表中具有完全相同的信息。我也必须验证这些。

我尝试对列表进行排序并使用 SequenceEqual 进行比较

Enumerable.SequenceEqual(ListA.OrderBy(s => s), ListB.OrderBy(s => s)

我遇到了以下错误

At least one object must implement IComparable.
Exception Stack trace is as below 

   at System.Collections.Comparer.Compare(Object a, Object b)
   at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y)
   at System.Linq.EnumerableSorter`2.CompareKeys(Int32 index1, Int32 index2)
   at System.Linq.EnumerableSorter`1.QuickSort(Int32[] map, Int32 left, Int32 right)
   at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
   at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__0.MoveNext()
   at System.Linq.Enumerable.SequenceEqual[TSource](IEnumerable`1 first, IEnumerable`1 second, IEqualityComparer`1 comparer)
   at System.Linq.Enumerable.SequenceEqual[TSource](IEnumerable`1 first, IEnumerable`1 second)

我该如何实现?如果你们能给我提供最快的方法会更好,因为 List 中的对象数量可能会增长到 1000 万。 感谢您的帮助!

编辑:每个员工都必须在两个列表中,顺序无关紧要。但是,如果 ListA 包含相同的员工对象 5 次(这意味着一些重复条目),而 ListB 包含员工对象 4 次,则 ListA 和 ListB 不相等。

最佳答案

您可以使用 SequenceEqual自定义 IEqualityComparer<Employee> :

class EmployeeComparer : IEqualityComparer<Employee>
{
    public bool Equals(Employee x, Employee y)
    {
        if (x == null || y == null) return false;

        bool equals = x.ID==y.ID && x.Name == y.Name && x.Dept == y.Dept 
            && x.Address == y.Address && x.Age == y.Age && x.Email == y.Email;
        return equals;
    }

    public int GetHashCode(Employee obj)
    {
        if (obj == null) return int.MinValue;

        int hash = 19;
        hash = hash + obj.ID.GetHashCode();
        hash = hash + obj.Name.GetHashCode();
        hash = hash + obj.Dept.GetHashCode();
        hash = hash + obj.Address.GetHashCode();
        hash = hash + obj.Age.GetHashCode();
        hash = hash + obj.Email.GetHashCode();
        return hash;
    }
}

现在很简单:

listA.SequenceEqual(ListB, new EmployeeComparer());

如果顺序不重要,您只想知道是否所有员工都在两个列表中,您可以使用 HashSet<Employee>.SetEquals确定两个列表是否包含相同的人:

var empComparer =  new EmployeeComparer();
bool bothEqual = new HashSet<Employee>(ListA, empComparer)
      .SetEquals(new HashSet<Employee>(ListB, empComparer));

关于c# - 检查两个 List<T> 是否相等的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236672/

相关文章:

c# - 在 ASP.NET 4.5 中的 AutoCompleteExtender 中添加滚动条

.NET Entity Framework

c# - 无法从另一个类访问列表

c# - 有没有办法用 DescriptorProto 反序列化未知对象?

.net - WPF 桌面应用程序中的 gRPC 服务器?

c# - 制作 DAL 的最佳方法是什么?

c# - 如何防止用户手动更改文件?

c# - 面向对象的类建模 C#

c# - 如何在 C# 中使用 Windows 搜索服务

c# - 如何从 Java 应用程序编译 c#/c++ 文件