1

I am trying to grab common values between two HashSets of the same type with identical lists, yet I get 0 values returned after the IntersectWith command. I am using the same list to begin with as a troubleshooting test, but eventually the value of returnlist will change as int y iterates through the sequence.

Debugging shows that comparelist.IntersectWith(returnlist); changes comparelist to 0 items. Just to clarify, returnlist and comparelist contain the same items in the same order.

CfgPersonQuery firstquery = new CfgPersonQuery();
firstquery.Filter.Add("skill_dbid", skills.First());
comparelist = new HashSet<CfgPerson>(confService.RetrieveMultipleObjects<CfgPerson>(firstquery));
foreach (int y in skills.Skip(1))
{
    try
    {
        CfgPersonQuery query = new CfgPersonQuery();
        query.Filter.Add("skill_dbid", skills.First());
        HashSet<CfgPerson> returnlist = new HashSet<CfgPerson>(
            confService.RetrieveMultipleObjects<CfgPerson>(query));
        comparelist.IntersectWith(returnlist);
    }
    catch
    {                    
        return null;
    }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Jon
  • 21
  • 6
  • Show us `CfgPerson` implementation. – apocalypse Jun 29 '17 at 17:39
  • Sorry, I'm not sure what specifically you're asking for. How can I go about obtaining that info for you? The CfgPerson object is part of an SDK I'm using. – Jon Jun 29 '17 at 17:41

1 Answers1

1

Since you do not own CfgPerson class and you cannot implement Equals method you should tell HashSet how to determine equality for that type. You can create HashSet using constructor which takes IEqualityComparer<T> as parameter.

So:

1) create class CfgPersonEqualityComparer : IEqualityComparer<CfgPerson> (need to read documentation how to do it)
2) var comparer = new CfgPersonEqualityComparer()
3) var hashSet1 = new HashSet(collection1, comparer)
4) var hashSet2 = new HashSet(collection2, comparer)
5) var result = hashSet1.IntersectWith(hashSet2) (it will automatically detect that both HashSets use the same equality comparers)

Or just create wrapper around CfgPerson which implements GetHasCode, Equals and IEquatable<CfgPerson>.

apocalypse
  • 5,764
  • 9
  • 47
  • 95
  • Thanks for this, I ended up building a custom IEqualityComparer for CfgPerson and it worked perfectly! – Jon Jun 29 '17 at 19:54