Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a unique hashcode for a JObject?

Tags:

c#

json.net

I'm trying to implement a cache for JObjects.

I was surprised to see that they didn't override the GetHashCode method and therefore, I can't use it as a unique key.

Since my json's are pretty large, I don't want to use JObject.ToString().GetHashCode as a solution.

I did see that they have an internal method called GetDeepHashCode but the implementation is based on other protected properties and therefore, I cannot "copy" the code and create an extension method from it.

I also don't want to use reflection and invoke the internal GetDeepHashCode method.

I'm looking for a way to create a unique cache key for a JObject and I don't want the method to be extra expensive when it comes to performance.

like image 486
Amir Popovich Avatar asked Sep 15 '16 09:09

Amir Popovich


People also ask

How do you create a hash code?

If you use eclipse, you can generate equals() and hashCode() using: Source -> Generate hashCode() and equals(). Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.

Is string GetHashCode unique?

No it is not unique. GetHashCode returns an Integer which has 2^32 possible values. However, there are clearly more than 2^32 strings that you could possibly construct. This guarantees that it cannot be unique.

How does GetHashCode work C#?

GetHashCode method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes.

What is the return type of the string GetHashCode?

Returns. A 32-bit signed integer hash code.


1 Answers

You can use JTokenEqualityComparer.GetHashCode(JToken token) for this purpose. It provides access to the GetDeepHashCode() method you saw.

var obj = JToken.Parse(jsonString);
var comparer = new JTokenEqualityComparer();
var hashCode = comparer.GetHashCode(obj);

Note that JTokenEqualityComparer.Equals(JToken x, JToken y) calls JToken.DeepEquals() (source) so this comparer is suited for use as an IEqualityComparer<JToken> when constructing hash tables or dictionaries of LINQ-to-JSON objects and uniqueness of values is desired.

like image 91
dbc Avatar answered Nov 03 '22 11:11

dbc