Home > Enterprise >  Separate out two identical collections except for different ids with LINQ
Separate out two identical collections except for different ids with LINQ

Time:03-30

I am trying to produce a method which feeds in two database (.db) files, loads them into an object which contains various string properties and a unique ID.

The db files were created from a LiteDB instance, with a unique ID assigned under the LiteDB library method, like so:

Id = ObjectID.NewObjectId();

I'm trying to obtain all items that are different between the two db collections, but unfortunately any LINQ query I try falls down because the IDs are always unique, despite all other values contained within the object being identical.

I would like to perform a LINQ query that will ignore the ID field in the object but do a comparison on all other properties within that object but am struggling to do so

My initial idea was to use

var differences = items1.Except(items2)

But this populates all items into the differences collection, due to the differing IDs.

Any advice on how to exclude the comparison of the ids would be appreciated, the tool may be used on millions of records so needs to be efficient.

CodePudding user response:

Except has an overload that accepts an IEqualityComparer<T>. You can implement this interface in a class in a way that ignores the ID and then pass an instance of that class to the method. See this example if you need a reference on how to implement IEqualityComparer<T>.

  • Related