c# - 两个可枚举之间的相等性

标签 c# linq ienumerable equality

我有两个具有完全相同引用元素的枚举,想知道为什么 Equals 不成立。

作为附带问题,下面比较每个元素的代码有效,但必须有更优雅的方法

var other = (ActivityService) obj;
if (!AllAccounts.Count().Equals(other.AllAccounts.Count())) return false;
for (int i = 0; i < AllAccounts.Count(); i++) {
    if (!AllAccounts.ElementAt(i).Equals(other.AllAccounts.ElementAt(i))) {
        return false;
    }
}
return true;

最佳答案

看看 Enumerable.SequenceEqual method .

bool result = AllAccounts.SequenceEqual(other.AllAccounts);

根据数据类型,您可能还需要使用 overloaded method接受 IEqualityComparer 来定义自定义比较方法。

关于c# - 两个可枚举之间的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2564983/

相关文章:

c# - 如何比较两个数据表的单元格值

c# - IEnumerable - 返回元素两侧范围内的项目

c# - Dapper 查询结果在对象中将表的 Pk 设置为 null

c# - 替换表达式主体中的参数名称

c# - 打开/关闭 'popped-up' 窗口时出现问题

entity-framework - 嵌套查询 Entity Framework

c# - 在一行中创建 IEnumerable 并将其传递给方法

c# - 连接多个 IEnumerable<T>

c# - 按对象的字段组合列表中的对象

C# 如果有 3 个 Form ,我可以显示 Form3 并关闭 Form1 和 Form2 吗?