不同
從 IEnumerable
返回唯一值。使用預設的相等比較器確定唯一性。
int[] array = { 1, 2, 3, 4, 2, 5, 3, 1, 2 };
var distinct = array.Distinct();
// distinct = { 1, 2, 3, 4, 5 }
要比較自定義資料型別,我們需要實現 IEquatable<T>
介面併為該型別提供 GetHashCode
和 Equals
方法。或者可以覆蓋相等比較器:
class SSNEqualityComparer : IEqualityComparer<Person> {
public bool Equals(Person a, Person b) => return a.SSN == b.SSN;
public int GetHashCode(Person p) => p.SSN;
}
List<Person> people;
distinct = people.Distinct(SSNEqualityComparer);