Last active
January 2, 2019 05:27
-
-
Save TheWorstProgrammerEver/79b10a47b7bd2329059cd0b9d33fc735 to your computer and use it in GitHub Desktop.
Object.Extend
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 ObjectExtend | |
{ | |
public static dynamic Extend(this object source, params object[] objs) | |
{ | |
var result = new ExpandoObject(); | |
var props = (IDictionary<string, object>)result; | |
foreach (var o in new[] { source }.Union(objs)) | |
{ | |
var expandoProperties = ( | |
o is ExpandoObject expando | |
? (IDictionary<string, object>)expando | |
: new Dictionary<string, object>()) | |
.Select(pair => new { Name = pair.Key, pair.Value }); | |
var typeProperties = o.GetType().GetProperties() | |
.Select(p => new {p.Name, Value = p.GetValue(o)}); | |
var properties = expandoProperties.Concat(typeProperties); | |
foreach (var p in properties) | |
{ | |
if (props.ContainsKey(p.Name)) props[p.Name] = p.Value; | |
else props.Add(p.Name, p.Value); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment