Created
August 28, 2012 21:06
-
-
Save gabrielgreen/3504363 to your computer and use it in GitHub Desktop.
CopyProperties
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
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