Home >Backend Development >C++ >Why Doesn't LINQ's Distinct Work as Expected with Custom Objects?

Why Doesn't LINQ's Distinct Work as Expected with Custom Objects?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-20 19:46:13764browse

Why Doesn't LINQ's Distinct Work as Expected with Custom Objects?

Understanding LINQ's Distinct Method Limitations with Custom Objects

LINQ's Distinct() method can be unpredictable when used with custom objects. The default behavior relies on object reference equality, not the equality of their properties. This means two distinct objects with identical property values will still be considered unique by Distinct().

To overcome this limitation, you need to define how your custom objects determine equality. A common solution is to implement the IEquatable<T> interface.

Implementing IEquatable for Custom Object Equality

Let's illustrate this with an Author class:

<code class="language-csharp">public class Author : IEquatable<Author>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public bool Equals(Author other)
    {
        if (other == null) return false;
        return FirstName == other.FirstName && LastName == other.LastName;
    }

    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = (FirstName != null ? FirstName.GetHashCode() : 0);
            hash = (hash * 397) ^ (LastName != null ? LastName.GetHashCode() : 0);
            return hash;
        }
    }
}</code>

This implementation defines equality:

  • Equals(Author other): This method compares the FirstName and LastName properties of two Author objects. It returns true if both properties are equal, and false otherwise. Null checks are included for robustness.

  • GetHashCode(): This method generates a hash code based on the FirstName and LastName properties. A consistent hash code is crucial for efficient Distinct() operation. The unchecked keyword and prime number multiplication improve hash code distribution.

By implementing Equals() and GetHashCode() correctly, you ensure that Distinct() considers objects with the same property values as equal, providing the expected results.

The above is the detailed content of Why Doesn't LINQ's Distinct Work as Expected with Custom Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn