Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...