Created
September 24, 2012 22:52
-
-
Save ChrisMissal/3778939 to your computer and use it in GitHub Desktop.
Creates a dynamic object from the differences of two strongly typed 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 class Diff | |
{ | |
public static dynamic GetDynamicDiff<T>(T left, T right) | |
{ | |
return GetDynamicDiff(left, right, typeof(T)); | |
} | |
private static dynamic GetDynamicDiff<T>(T left, T right, Type type) | |
{ | |
dynamic expando = new System.Dynamic.ExpandoObject(); | |
var properties = type.GetProperties(); | |
foreach (var leftProperty in properties) | |
{ | |
var rightProperty = type.GetProperty(leftProperty.Name); | |
var leftValue = leftProperty.GetValue(left, null); | |
var rightValue = rightProperty.GetValue(right, null); | |
if (leftProperty.PropertyType.IsValueType && !object.Equals(leftValue, rightValue)) | |
{ | |
((IDictionary<string, object>)expando).Add(leftProperty.Name, rightValue); | |
} | |
else if (!leftProperty.PropertyType.IsValueType && !(leftValue is string)) | |
{ | |
var diff = GetDynamicDiff(leftValue, rightValue, leftProperty.PropertyType); | |
if (!((IDictionary<string, object>)diff).Any()) | |
continue; | |
((IDictionary<string, object>)expando).Add(leftProperty.Name, ((IDictionary<string, object>)diff).Any() ? diff : null); | |
} | |
else if (!object.Equals(leftValue, rightValue)) | |
{ | |
((IDictionary<string, object>)expando).Add(leftProperty.Name, rightValue); | |
} | |
} | |
return expando; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment