LINQ to Objects compares items to themselves because its default equality comparer, EqualityComparer<T>.Default, calls an object's own Equals method (and GetHashCode) to decide whether two references or values are equal. When you use operators such as Distinct, GroupBy, Union, Intersect, Except, Contains, or Join, the query must determine whether two elements are the same, and the standard mechanism is to ask one element whether it equals another—often effectively comparing an item with itself when the same instance appears more than once or when the comparer is invoked on the element itself.
Background: What LINQ to Objects Actually Does
LINQ to Objects is the set of extension methods in System.Linq.Enumerable that operate on in-memory collections implementing IEnumerable<T>. Unlike LINQ to SQL or Entity Framework, which translate expression trees into SQL, LINQ to Objects executes ordinary .NET delegates in-process. The operators are implemented in the .NET runtime library and rely on the standard equality and comparison contracts defined by the Base Class Library.
When an operator needs to compare two elements, it does not inspect their fields directly. Instead it uses an IEqualityComparer<T>. If you do not supply one, the operator falls back to EqualityComparer<T>.Default. That default comparer is a singleton that knows how to call Equals and GetHashCode on the type T. For reference types that do not override Equals, this resolves to object.ReferenceEquals; for value types it resolves to field-by-field value equality; for types that override Equals, it calls that override.
The phrase “compares items to themselves” is therefore a shorthand for a design in which each element is the authority on its own equality. The query does not hold a separate table of identities; it asks the item.
How the Default Comparer Works Under the Hood
Understanding the mechanics clarifies why self-comparison appears. The default comparer is created once per closed generic type and cached. When an operator such as Distinct runs, it builds a hash set keyed by GetHashCode and then, for each candidate, calls Equals to resolve hash collisions. The call is literally comparer.Equals(existingItem, candidateItem). If existingItem and candidateItem are the same reference, the comparison is an item against itself—a case that must return true for correctness.
Several operators rely on this contract:
DistinctandUnionuse a set to suppress duplicates, comparing each new element against elements already stored.GroupByandToLookupuse a hash table to assign each element to a group key.IntersectandExceptbuild a set from one sequence and probe it with elements from the other.JoinandGroupJoinhash the inner sequence and probe it with outer elements.Contains,SequenceEqual, andMax/Minwith a comparer also invoke equality or comparison logic on the elements.
In every case, the element itself provides the equality semantics unless you override them.
Why the Design Uses Self-Comparison Instead of External Identity
The .NET equality contract is deliberately object-centric. The object.Equals method, IEquatable<T>, and IComparable<T> are all defined so that an instance can answer questions about itself. This makes LINQ operators composable without a central registry of identities. It also means the same operators work for value types, reference types, strings, and custom classes without special cases.
Self-comparison also supports mutable objects and proxies. If an operator stored an external identity map, it would need to know how to key every type. By delegating to the element, LINQ stays agnostic about what “equal” means for a given domain. The trade-off is that the element's implementation controls correctness: if Equals and GetHashCode are inconsistent, operators misbehave.
A common misconception is that LINQ compares items to themselves because of a bug or an optimization quirk. In fact it is the documented behavior of the equality contract. The runtime does include a fast path: EqualityComparer<T>.Default may check reference equality before calling a user-defined Equals, and HashSet<T> short-circuits when the incoming reference is already in the set. Those are optimizations, not the reason for the design.
Common Problems Caused by the Default Behavior
Because the element supplies equality, mistakes in Equals or GetHashCode surface as incorrect query results. Typical symptoms include:
Distinctreturning duplicates becauseGetHashCodewas not overridden alongsideEquals.GroupBycreating separate groups for objects that look identical but are different references and use reference equality.Containsreturningfalsefor a value that appears equal by field values but not by the type's equality rules.Joinproducing no matches when the key type's equality is case-sensitive or culture-sensitive in an unexpected way.- Exceptions from
GetHashCodeon mutable objects whose hash changes after being placed in a set.
These are not LINQ bugs. They are consequences of the element being the source of truth.
How to Control Comparison When the Default Is Wrong
You can override the default in three main ways, each with different scope and cost.
- Override
EqualsandGetHashCodeon the type. This changes equality for every LINQ query and every dictionary or set that uses the type. It is the most invasive option and should be done only when the type has a natural value identity. - Implement
IEquatable<T>. This avoids boxing for value types and gives a strongly typed equality method, but it still defines equality on the type itself. - Pass an
IEqualityComparer<T>to the operator. This is the most targeted option. You can supply a comparer for a single query without changing the type. The comparer can compare by a projection, by case-insensitive string rules, or by a composite key.
For example, to group orders by a case-insensitive customer name without altering the Customer class, pass StringComparer.OrdinalIgnoreCase to GroupBy via a key selector and comparer overload. To compare by multiple fields, create a small comparer class or use a tuple key with the default tuple equality.
When choosing, consider:
- Scope: type-level equality affects all code; a comparer affects one call site.
- Performance: custom comparers add virtual calls; overriding on the type can be inlined by the runtime.
- Consistency: if the type is used as a dictionary key elsewhere, its equality should match the intended domain identity.
- Mutability: avoid mutable fields in
GetHashCode; prefer immutable keys or comparers that compute stable hashes.
How LINQ to Objects Differs from Query Providers
LINQ to SQL, Entity Framework, and other IQueryProvider implementations do not execute Equals in memory. They translate comparisons into SQL or another query language, where equality is defined by the database collation and column types. As a result, a query that works in LINQ to Objects may behave differently when run against a database, especially for strings, nulls, and case sensitivity. The self-comparison model is specific to in-memory execution.
Similarly, PLINQ parallelizes LINQ to Objects but preserves the same equality contract. The difference is concurrency: comparers must be thread-safe if shared across partitions.
Frequently Asked Questions
Does LINQ to Objects literally call Equals on the same object?
It can. When the same reference appears twice in a sequence, the set-based operators may compare that reference with itself. The equality contract requires that an object equals itself, so the result is true.
Why does Distinct not remove duplicates in my custom class?
Most likely the class uses reference equality because it does not override Equals and GetHashCode. Two separate instances with identical field values are not equal under reference equality. Override both methods or pass an IEqualityComparer<T>.
Is it safe to rely on the default comparer for strings?
The default string comparer is ordinal, meaning it compares by UTF-16 code units, not by culture. That is usually correct for identifiers and keys but may surprise you for user-facing text. Use StringComparer explicitly when culture or case rules matter.
Can I make LINQ compare by a subset of fields without changing the class?
Yes. Project to an anonymous type or tuple containing only the fields you want, then call Distinct or GroupBy on that projection. Anonymous types and tuples implement value equality over their members.
Why does GroupBy create groups in a different order than I expect?
GroupBy preserves the order of first appearance of each key in the source sequence, but the internal hash table does not guarantee enumeration order of groups in all implementations. If order matters, sort the results explicitly.
Does overriding Equals affect performance?
It can. A poorly implemented GetHashCode that causes many collisions turns set operations into linear scans. Keep hash codes well distributed and consistent with Equals.