I have a class, called ClassX for the purposes of this question, declared as follows:
class X
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
If I have two instances (instanceOne and instanceTwo) of List<T> of these classes, how can I find the elements that are the same in both instances:
Assume that there is two elements in instanceOne and four elements in instanceTwo. Two of the elements are the same (as defined by the fact that they have the same Guid Id) in each of the instances
I thought I should be able to LINQ my way to it but this isn’t doing it for me
// What's common to the two instances?
var commonElements = (
from a in instanceTwo
join b in instanceOne on a.Id equals b.Id
select b).ToList();
// What's not in instanceOne and in instanceTwo?
var notInInstanceOne = instanceTwo.Except(commonElements)
In this situation instanceTwo is a superset of instanceOne but this may not always be the case so I should be able to flip the original LINQ statement to get the elements in instanceOne that are not in instanceTwo viz:
var notInInstanceTwo = instanceOne.Except(commonElements)
Frustratingly the original LINQ statement (where I attempt to determine the common elements) isn’t working, can anyone spot what I’m doing wrong?
EDIT 2012-06-08 11:00 UTC
Per @Nikhil Agrawal and @Trust me – I’m a Doctor I have used the Intersect method but this doesn’t produce the expected results:
var commonItems = instanceTwo.Intersect(instanceOne); // Returns nothing
var itemsInTwoNotOne= instanceTwo.Except(instanceOne); // Returns everything in instanceTwo
FWIW my implementation of the Equals() method is:
public bool Equals(Guid x, Guid y)
{
if (x == y)
{
return true;
}
return false;
}
Use can use intersect to get a list of all common elements. You should also create a IEqualityComparer, since you want to identify the elements by its Id.
Example: