Comparing C # Objects Using Json

I want to compare two objects without implementing the Equals () method.

What are the disadvantages of comparing them this way: 1. Sorting them out with Json 2. comparing the results

thanks!

+4
source share
4 answers

What are the disadvantages of comparing them in this way.

Loss of speed. Converting objects to JSON strings and then comparing them is much slower than using the equals property.

Implementing Equals() is always the best way to compare two objects for equality.

+7
source

The downside is that you need to serialize them, which is potentially slow and certainly slower than the Equals implementation.

You may also find yourself in the part of the objects that you need to compare without being serialized and therefore not getting a true comparison.

+3
source

During the serialization process, there is some overhead for converting objects to json. You will need to check if the invoice is suitable for your situation.

Aside, the source of the json object is troubling. I saw a couple of different json serializers formatting objects in different ways (for example, quoting property names and not quoting them). Such things may give you incorrect results.

+2
source

Perhaps with such a class you can do this work (BsonDocument is a class from MongoDBDriver):

  public class Comparer { private object first, second; public Comparer(object first, object second) { this.first = first; this.second = second; } public List<string> Compare() { if (first.GetType() != second.GetType()) { return null; } BsonDocument firstDoc = first.ToBsonDocument(); BsonDocument secondDoc = second.ToBsonDocument(); return Compare(firstDoc, secondDoc); } private List<string> Compare(BsonDocument first, BsonDocument second) { List<string> changedFields = new List<string>(); foreach (string elementName in first.Names) { BsonElement element = first.GetElement(elementName); if (element.Value.IsBsonDocument) { BsonDocument elementDocument = element.Value.AsBsonDocument; BsonDocument secondElementDocument = second.GetElement(element.Name).Value.AsBsonDocument; if (elementDocument.ElementCount > 1 && secondElementDocument.ElementCount == elementDocument.ElementCount) { foreach (string value in (Compare(elementDocument, secondElementDocument))) { changedFields.Add(value); } } else { changedFields.Add(element.Name); } } else if (element.Value != second.GetElement(element.Name).Value) changedFields.Add(element.Name); } return changedFields; } } 
+1
source

All Articles