Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What C#/Linq code copies all matching property name values between two objects without knowing their type?

Tags:

c#

reflection

I have a well known POCO class of Customer to return from my method. However, I only populate properties specified by an ever changing Expression p => new {p.id, p.name} for example, as a parameter to the method.

Somehow I need to copy all matching fields between these two objects.

var returnObject = IList<Customer>();
var partialFieldObject = DC.Customers.Select( expParameter); // wont know the fields

foreach( var partialRecord in partialFieldObject)
{    foreach (var property in partialRecord // Pseudo code)
     {
         returnObject[property] = property.value; // More Pseudo code
     }
}
End result is a strongly typed Customer POCO returned that only has the selected fields populated with values.
like image 993
Zachary Scott Avatar asked Oct 28 '10 04:10

Zachary Scott


1 Answers

Some simple reflection does the trick, assuming the properties on partialFieldObject line up exactly (case-sensitive) with properties on Customer...

void SetProperties(object source, object target)
{
    var customerType = target.GetType();
    foreach (var prop in source.GetType().GetProperties())
    {
        var propGetter = prop.GetGetMethod();
        var propSetter = customerType.GetProperty(prop.Name).GetSetMethod();
        var valueToSet = propGetter.Invoke(source, null);
        propSetter.Invoke(target, new[] { valueToSet });
    }
}
like image 99
dahlbyk Avatar answered Oct 04 '22 01:10

dahlbyk