Question:
There are lists of complex objects. You need to somehow compare them. An attempt to use List.Distinct<>
and other methods for some reason fails.
Answer:
The difference of the lists is found using the Except
method:
double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };
IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
Intersection – using the Intersect
method:
int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
IEnumerable<int> both = id1.Intersect(id2);
In order for these methods to work on complex objects, the comparison operator must be overridden in the classes of these objects. If you cannot redefine the comparison operator for some reason, you can use versions of the Except
and Intersect
methods, which are passed as the second parameter a comparator – an object of a class that implements the IEqualityComparer
interface, which contains the logic for comparing objects of your class.
The Distinct
method didn't work because it returns the unique elements of one collection, not the intersection or difference of the two collections. It also requires an overridden comparison operator or comparator to work correctly.