Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

c# - How can I create a unique hashcode for a JObject?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...