I have the following class called SearchItem, which extends another class called Claim. For brevity, I’m simply including the class names and their properties.
public class SearchItem : Claim {
public int FileStreamID { get; set; }
public Int16 UploadedByLabID { get; set; }
public string FileName { get; set; }
public string TypeDesc { get; set; }
public string UploadedByLab { get; set; }
public string UploadedByUser { get; set; }
public DateTime? UploadDate { get; set; }
}
public class Claim {
public int ClaimID { get; set; }
public string DOB_Format {
get {
string s = "";
if (this.DOB.HasValue)
s = this.DOB.Value.ToString("MM/dd/yyyy");
return s;
}
}
public string FirstName { get; set; }
public string FullClaimDesc {
get {
return this.FullName + " (" + this.SSN_Mask + ")";
}
}
public string FullName {
get {
string s = this.LastName + ", " + this.FirstName;
if (!string.IsNullOrEmpty(this.MiddleName))
s += " " + this.MiddleName;
return s;
}
}
public string LastName { get; set; }
public string MiddleName { get; set; }
public string SSN { get; set; }
public string SSN_Mask {
get {
string s = "";
if (this.SSN.Length > 0)
s = Claim.FormatHyphens(this.SSN);
return s;
}
}
public string Suffix { get; set; }
public DateTime? DOB { get; set; }
public DateTime? RequestDate { get; set; }
public Int16 OwnedByLabID { get; set; }
public List<Int16> lstLabRecipientID { get; set; }
}
I have two lists that contains n SearchItems.
List<SearchItems> lstMain = new List<SearchItems>();
List<SearchItems> lstTemp = new List<SearchItems>();
Assume that lstMain contains 25 SearchItems and lstTemp contains 5 SearchItems. What I would like to do is use Intersect in order to retrieve the SearchItems that are the same between lstMain and lstTemp.
IEnumerable<SearchItem> results = lstMain.Intersect(lstTemp);
However, results always comes up empty. I am certain that the two lists contains 3 SearchItems that are identical, and by identical I mean that their properties yield the same values (ie – lstMain[2].ClaimID = 965 and lstTemp[0].ClaimID = 965, etc.).
So am I expecting too much out of the Intersect extension method? Can it not handle complext types that implement inheritance?
Since I assume the class instances for the items that are considered “the same” are different in both lists you need a custom
IEqualityComparer<SearchItem>to useIntersect(), you can pass it as a second parameter.In your implementation of
IEqualityComparer<SearchItem>you would then have to compare the properties of twoSearchIteminstances to determine if they should be considered equal, an example can be found here.