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>
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>
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>
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>
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!