Skip to content

Instantly share code, notes, and snippets.

@TheWorstProgrammerEver
Last active January 2, 2019 05:27
Show Gist options
  • Save TheWorstProgrammerEver/79b10a47b7bd2329059cd0b9d33fc735 to your computer and use it in GitHub Desktop.
Save TheWorstProgrammerEver/79b10a47b7bd2329059cd0b9d33fc735 to your computer and use it in GitHub Desktop.
Object.Extend
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