Skip to content

Instantly share code, notes, and snippets.

@gabrielgreen
Created August 28, 2012 21:06
Show Gist options
  • Save gabrielgreen/3504363 to your computer and use it in GitHub Desktop.
Save gabrielgreen/3504363 to your computer and use it in GitHub Desktop.
CopyProperties
static void CopyProperties(object sourceObject, object targetObject, bool deepCopy = true)
{
if (sourceObject != null && targetObject != null)
{
(from sourceProperty in sourceObject.GetType().GetProperties().AsEnumerable()
from targetProperty in targetObject.GetType().GetProperties().AsEnumerable()
where sourceProperty.Name.ToUpper() == targetProperty.Name.ToUpper()
let sourceValue = sourceProperty.GetValue(sourceObject, null)
where sourceValue != null
select CopyProperty(targetProperty, targetObject, sourceValue, deepCopy))
.ToList()
.ForEach(c => c());
}
}
static Action CopyProperty(PropertyInfo propertyInfo, object targetObject, object sourceValue, bool deepCopy)
{
if (!deepCopy || sourceValue.GetType().FullName.StartsWith("System."))
return () => propertyInfo.SetValue(targetObject, sourceValue, null);
else
return () => CopyProperties(sourceValue, propertyInfo.GetValue(targetObject, null));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment