Home >Backend Development >C++ >How to Ensure Correct Object Equality for LINQ's Distinct Method with Custom Objects?

How to Ensure Correct Object Equality for LINQ's Distinct Method with Custom Objects?

Linda Hamilton
Linda HamiltonOriginal
2025-01-20 19:41:14509browse

How to Ensure Correct Object Equality for LINQ's Distinct Method with Custom Objects?

Use IEquatable to handle object equality in LINQ Distinct

LINQ's Distinct method is designed to identify unique objects based on their equality. However, with custom objects, it may not always work as expected.

In the provided example, the Distinct method failed to identify two Author objects with the same name as duplicates. This is because LINQ treats objects as distinct based on their reference addresses rather than their property values.

In order to solve this problem, the Author interface can be implemented in the IEquatable class. By overriding the Equals method, you can define custom logic to determine equality based on property values ​​FirstName and LastName. The following implementation checks matching values ​​in two fields to determine equality:

<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 (FirstName == other?.FirstName && LastName == other?.LastName)
            return true;

        return false;
    }

    // 为保持一致性而重写GetHashCode
    public override int GetHashCode()
    {
        return (FirstName?.GetHashCode() ?? 0) ^ (LastName?.GetHashCode() ?? 0);
    }
}</code>

Usage:

Applying this custom implementation solves Distinct's problem. The modified code correctly identifies duplicate Author objects and removes one of them from the results:

<code class="language-csharp">using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        // 使用重复作者初始化书籍列表
        List<Book> books = new List<Book>
        {
            new Book
            {
                Name = "C# in Depth",
                Authors = new List<Author>
                {
                    new Author { FirstName = "Jon", LastName = "Skeet" },
                    new Author { FirstName = "Jon", LastName = "Skeet" },
                }
            },
            // ...
        };

        // 选择作者,应用Distinct,并打印
        var temp = books.SelectMany(book => book.Authors).Distinct();
        foreach (var author in temp)
        {
            Console.WriteLine($"{author.FirstName} {author.LastName}");
        }

        Console.Read();
    }
}</code>

Conclusion:

Implementing IEquatable and overriding the Equals method allows customizing the definition of object equality in LINQ operations. This ensures that Distinct methods correctly handle custom objects based on their properties rather than reference addresses.

Note that the GetHashCode method has been improved in the code example to ensure consistency with the Equals method and uses the null-conditional operator (?.) to handle potentially null properties. This avoids potential NullReferenceException exceptions.

The above is the detailed content of How to Ensure Correct Object Equality for LINQ's Distinct Method 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