Computing Deep Hash Codes using LINQ to XML

In some scenarios, it is useful to compute a ‘deep’ hash code using LINQ to XML.  If you are writing a server-side application that caches queries expressed in XML, then you may want to store these queries in a hash table.  XNode (and XElement) inherit the GetHashCode method from object, which returns a hash code based on object identity, which doesn’t help in these scenarios.  However, there is a method, XNodeEqualityComparer.GetHashCode, which computes a deep hash code.  It’s part of the LINQ to XML API, but it’s not very discoverable via Intellisense, so some folks don’t know about it.

This blog is inactive.
New blog:

Blog TOCThis is related to XNode.DeepEquals, which compares the values of two nodes, including the values of all descendant nodes.

And of course, before computing your deep hash code, you may want to normalize the XML tree, which eliminates trivial differences between trees that will cause computation of different hash codes for semantically identical trees.