23 November 2010

How do I – Write my own C Sharp IEqualityComparor when System.Collections.Generic.List.Contains(System.Xml.Linq.XNode) fails and does not work as expected

Unfortunately I ran into an issue with the C# List<T> class the other day.  I was in need of checking for a given XML snippet’s existence in an XML document.  I immediately jumped in and tried using Linq2Xml and List<T> to solve the problem.  The way I figured it, I could grab a quick list of XNodes from the XML document and then using the .Contains() method, I could check if the node in the XML snippet exists in the list.  Imagine my surprise when I ran through the code, but for some reason, the .Contains() method did NOT return true even on an identical match.  Weird.  :S
After spending some time trying to figure out why it wasn’t working as advertised (as I’ve mentioned before, 80% of a developer’s time is spent figuring out why something isn’t working as advertised or published) I decided to go the easier route and leverage the .Contains() method’s second overloaded form which takes an IEQualityComparor so all I’d have to do is write my own IEQualityComparor derived class and pass it to the .Contains() method.  Let’s take a look at how we do this.


In this post we’ve shown how to create our very own IEqualityComparor method to use for our purposes since the List<XNode>.Contains() method doesn’t function the way we needed it to.  I would venture to say, that the .Contains() method without our IEqualityComparor is pretty much useless.
Of course, if anyone out there can explain to me why it works the way it does and how the way it works is actually useful, I’m all ears. 🙂


Cheers
C

No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...