dotnet / dotnet/dotnet-api-docs

Enumerable.Distinct requires the GetHashCode override to work on default comparer

Aperta
#3,572 1 commento 0 reazioni 0 assegnatari Vedi su GitHub
area-System.Linq help wanted Pri3
Lingua principale
C#
Stelle
949
Fork
1.7k
Merge medio
2g 19h
PR unite (30g)
52

Descrizione

The docs say (https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?view=netframework-4.8#System_Linq_Enumerable_Distinct__1_System_Collections_Generic_IEnumerable___0__)

>If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the `IEquatable` generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide `GetHashCode` and `Equals` methods.

This is confusing and wrong. `IEquatable` interface only (!) requires to implement the `bool Equals(T other);` method. However, inside `Distinct()` (and probably other similar methods such as group by, etc) also compares the hash codes of the object, which it takes from the `EqualityComparer.Default`, which, while being created for an implementation of `IEquatable`, that does not have the override for `GetHashCode(T object)`, uses the default `T.GetHashCode()`.

Consequence: if I follow the "must" part of the doc and implement ONLY `IEquatable` interface, that method (`bool Equals(T other);`) even isn't being called! Which naturally totally confuses me as for what did I do wrong.

How to fix: TBH I'd say the implementation here with `IEquatable` itself is very questionable. It should've been IEqualityComparer. But for the docs, please at least add the note that "If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the `IEquatable` generic interface in the class **AND override the inherited `GetHashCode()` method. For consistency, after that you should also override the inherited `Equals()` method.** ..."

Guida per i contributori

Apri la guida per i contributori

Direzione di ricerca

Inizia dalla documentazione dell'API Enumerable.Distinct collegata e individua il relativo esempio di tipo personalizzato e le indicazioni associate. Confronta la formulazione con la questione dell'issue relativa a Equals/GetHashCode, quindi aggiorna la pagina in modo che le indicazioni sull'uguaglianza siano corrette e verifica la documentazione renderizzata.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
csharp
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.