Home > Backend Development > C++ > How Can I Efficiently Find the Difference Between Two Lists of Custom Objects in C#?

How Can I Efficiently Find the Difference Between Two Lists of Custom Objects in C#?

Patricia Arquette
Release: 2025-01-23 00:44:11
Original
721 people have browsed it

How Can I Efficiently Find the Difference Between Two Lists of Custom Objects in C#?

Difference extraction of generic custom object lists in C#

Suppose you have two lists, each containing custom objects, and you need a way to get a third list that only contains items that are present in the first list but not in the second element.

For this purpose, the .Except() method is a suitable option. This method assumes that your custom object implements the Equals and GetHashCode methods, thus providing a way to define object equality. Using .Except() is simple:

<code class="language-csharp">var list3 = list1.Except(list2).ToList();</code>
Copy after login

However, if you need to custom define equality based on a specific property (such as ID), you can define a IEqualityComparer<T> implementation. Consider the following example:

<code class="language-csharp">public class IdComparer : IEqualityComparer<CustomObject>
{
    public int GetHashCode(CustomObject co)
    {
        if (co == null)
        {
            return 0;
        }
        return co.Id.GetHashCode();
    }

    public bool Equals(CustomObject x1, CustomObject x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }
        if (object.ReferenceEquals(x1, null) ||
            object.ReferenceEquals(x2, null))
        {
            return false;
        }
        return x1.Id == x2.Id;
    }
}</code>
Copy after login

In this case you can use the following code to retrieve the difference between the two lists:

<code class="language-csharp">var list3 = list1.Except(list2, new IdComparer()).ToList();</code>
Copy after login

For cases where duplicates exist, consider creating a set from the second list and use the following method:

<code class="language-csharp">var list3 = list1.Where(x => !set2.Contains(x)).ToList();</code>
Copy after login

This will ensure that duplicates are retained in the results list.

The above is the detailed content of How Can I Efficiently Find the Difference Between Two Lists of Custom Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template