簡體   English   中英

兩個枚舉之間的平等

[英]Equality between two enumerables

我有兩個具有完全相同的參考元素的枚舉,並想知道為什么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方法

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

根據數據類型,您可能還需要使用接受IEqualityComparer重載方法來定義自定義比較方法。

.Equals比較了枚舉的引用,而不是它們包含的元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM