I know this question has been answered, but I feel like this is a perfect case for the SequenceEqual method. Rather than having to handle the 2 equalitycomparers in the same layer you can change your code into one line--a SequenceEqual() call that kicks off another SequenceEqual inside the comparer to test the versions. So in the outer equalitycomparer you could do the comparison of the Id and then call another SequenceEqual on the Versions collections of both.
Modifying Dion's example above to use SequenceEqual, the revamped comparers:
UPDATE: Object.Equals is not going to work for you. You need to compare the properties if you want objects that aren't the exact same but have the exact same values for properties.
public class DocumentTypeComparer : IEqualityComparer<DocumentType>
public bool Equals(DocumentType docType1, DocumentType docType2)
return !(docType1 == null || docType2 == null)
&& docType1.Id == docType2.Id
&& docType1.Versions.SequenceEqual(doctype2.Versions, new DocumentTypeVersionComparer());
public class DocumentTypeVersionComparer : IEqualityComparer<DocumentTypeVersion>
public bool Equals(DocumentTypeVersion docTypeVersion1, DocumentTypeVersion docTypeVersion2)
if (docTypeVersion1.ReferenceEquals(docTypeVersion2)) return true;
return !(Object.ReferenceEquals(docTypeVersion1, null) || Object.ReferenceEquals(docTypeVersion2, null))
&& docTypeVersion1.SomeProperty == docTypeVersion2.SomeProperty
&& docTypeVersion1.SomeOtherProperty == docTypeVersion2.SomeOtherProperty);
And your one-liner to check whether the collections differ:
var collectionsMatch = documentTypes.SequenceEqual(importedDocumentTypes, new DocumentTypeComparer());
Example one-liner using possible sorting method:
var collectionsMatch = documentTypes.OrderBy(d => d.Id).SequenceEqual(importedDocumentTypes.OrderBy(d => d.Id), new DocumentTypeComparer());
Note that you will have to sort your collections before doing a comparison. I didn't include what to sort on because that's up to your implementation, but I recommend doing the ordering of
Versions inside the DocumentTypeComparer, you don't want the DocumentTypeComparer to only work when the collections it's applied to have a sorted Version property. Also when implementing IEqualityComparer you will have to implement
GetHashCode (resources below).
Example implementation of GetHashCode from MSDN:
Discussion on best way to implement the method: