Created
December 22, 2011 20:33
-
-
Save chrisnicola/1511744 to your computer and use it in GitHub Desktop.
Mongo C# extension to compare BsonDocument and BsonValue objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static bool SameAs(this BsonDocument source, BsonDocument other, params string[] ignoreFields) | |
{ | |
var elements = source.Elements.Where(x => !ignoreFields.Contains(x.Name)).ToArray(); | |
if (elements.Length == 0 && other.Elements.Where(x => !ignoreFields.Contains(x.Name)).Any()) return false; | |
foreach (var element in source.Elements) | |
{ | |
if (ignoreFields.Contains(element.Name)) continue; | |
if (!other.Names.Contains(element.Name)) return false; | |
var value = element.Value; | |
var otherValue = other[element.Name]; | |
if (!value.SameAs(otherValue)) return false; | |
} | |
return true; | |
} | |
public static bool SameAs(this BsonValue value, BsonValue otherValue) | |
{ | |
if (value.IsBsonDocument) | |
{ | |
if (!otherValue.IsBsonDocument) return false; | |
if (!value.AsBsonDocument.SameAs(otherValue.AsBsonDocument)) return false; | |
} | |
else if (value.IsBsonArray) | |
{ | |
if (!otherValue.IsBsonArray) return false; | |
if (value.AsBsonArray.Count != otherValue.AsBsonArray.Count) return false; | |
var array = value.AsBsonArray.OrderBy(x => x).ToArray(); | |
var otherArray = otherValue.AsBsonArray.OrderBy(x => x).ToArray(); | |
return !array.Where((t, i) => !t.SameAs(otherArray[i])).Any(); | |
} | |
else return value.Equals(otherValue); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment