Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 865445
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T09:38:27+00:00 2026-05-15T09:38:27+00:00

Im creating a collection of (dynamically generated type) for display in a silverlight grid

  • 0

Im creating a collection of (dynamically generated type) for display in a silverlight grid and one of the processes involves creating an import (dynamically generated type) type then mapping the properties on the import type to the collection of (dynamically generated type) both types share a Id property that identifies the item ( be it on the grid or in the import)

ie
type bound to grid

 int Id {get; set}     
 string Foo {get;set;}
 string FooFoo {get;set;}

and import the type

 int Id {get; set}
 string Foo {get;set}

where ids match i want to copy foos.

What is a fast way to map properties from the one type to another in a collection?

EDIT

Heres the final Typemapper implementation with thanks to Stephan, as a feature will only map the two types when the keymembers are equal, mappings defined via a dictionary string string representing the member names, works in silverlight.

public class TypeMapper
{ 
    private readonly DynamicMethod _mapper;


    public static DynamicMethod BuildMapper(Type fromType, 
                                            Type toType,
                                            KeyValuePair<string, string> keyMemberMap,
                                            Dictionary<string, string> memberMappings)
    {

        var method = new DynamicMethod("Map", typeof(bool), new[] { fromType, toType });

        // Preparing Reflection instances
        MethodInfo getFromKeyMethod = fromType.GetMethod(
            string.Format("get_{0}", keyMemberMap.Key),
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        MethodInfo getToKeyMethod = toType.GetMethod(
            string.Format("get_{0}", keyMemberMap.Value),
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        ILGenerator gen = method.GetILGenerator();

        // Preparing locals
        gen.DeclareLocal(typeof(Boolean));
        // Preparing labels
        Label labelNoMatch = gen.DefineLabel();
        // Writing body
        gen.Emit(OpCodes.Ldarg_0);
        gen.Emit(OpCodes.Callvirt, getFromKeyMethod);
        gen.Emit(OpCodes.Ldarg_1);
        gen.Emit(OpCodes.Callvirt, getToKeyMethod);
        gen.Emit(OpCodes.Ceq);
        gen.Emit(OpCodes.Stloc_0);
        gen.Emit(OpCodes.Ldloc_0);
        gen.Emit(OpCodes.Brfalse_S, labelNoMatch);
        gen.Emit(OpCodes.Ldarg_1);
        gen.Emit(OpCodes.Ldarg_0);


        foreach (var mapping in memberMappings)
        {
            var getFromValueMethod = fromType.GetMethod(
               string.Format("get_{0}", mapping.Key),
               BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            var setToValueMethod = toType.GetMethod(
                string.Format("set_{0}", mapping.Value),
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            gen.Emit(OpCodes.Callvirt, getFromValueMethod);
            gen.Emit(OpCodes.Callvirt, setToValueMethod);
        }

        gen.MarkLabel(labelNoMatch);
        gen.Emit(OpCodes.Ldloc_0);
        gen.Emit(OpCodes.Ret);


        return method;
    }

    public void Map (object fromInstance, object toInstance)
    {
        _mapper.Invoke(null, new[] { fromInstance, toInstance });
    }


    public TypeMapper(Type fromType, Type toType, 
        KeyValuePair<string, string> keyMemberMap, 
        Dictionary<string, string> memberMappings)
    {
        _mapper = BuildMapper(fromType, toType, keyMemberMap, memberMappings); 
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T09:38:27+00:00Added an answer on May 15, 2026 at 9:38 am
    bound.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList()
        .ForEach(s => 
            {
                var prop = import.GetType().GetProperty(s.Name,BindingFlags.Public | BindingFlags.Instance);
                if(prop != null)
                {
                    prop.SetValue(import,s.GetValue(bound,null),null);
                }
            });
    

    That will map properties from one item to another. If you want to do it in a collection make that a method and do myCollection.Select(o => MapProperties(o,mapType));.

    Note: The method currently uses an existing object and copies into it. You could have your method except a type and then call Activator.CreateInstance(type) and set that to the value of import for my snippet.

    Edit

    Dynamic Methods

    This article has a good example of generating a DynamicMethod to do the deep copy of dynamic objects. It will have a much longer setup time then the reflection solution, but each subsequent call will be as fast as if compiled.

    Edit

    Actual Example:

    DynamicMethod GetMapper(Type type1, Type type2)
    {
    DynamicMethod method = new DynamicMethod("junk", type2,
    new Type[] { type1 });
    
    ILGenerator il = method.GetILGenerator();
    
    LocalBuilder obj0 = il.DeclareLocal(type2); //target
    
    // create object and store in local 0
    ConstructorInfo ctor = type2.GetConstructor(
      new Type[] { });
    il.Emit(OpCodes.Newobj, ctor);
    il.Emit(OpCodes.Stloc_0);
    
    
    PropertyInfo[] properties = type1.GetProperties(BindingFlags.Instance
    | BindingFlags.Public | BindingFlags.FlattenHierarchy);
    foreach (PropertyInfo prop in properties)
    {
    // local constructed object
    il.Emit(OpCodes.Ldloc_0);
    
    // load source argument
    il.Emit(OpCodes.Ldarg_0);
    
    // get property value
    il.EmitCall(OpCodes.Callvirt, type1.GetMethod(
        "get_" + prop.Name), null);
    il.EmitCall(OpCodes.Callvirt, type2.GetMethod(
        "set_" + prop.Name), null);
    }
    
    il.Emit(OpCodes.Ldloc_0);
    il.Emit(OpCodes.Ret);
    return method;
    }
    

    You should be able to do GetMapper(sourceType,destinationType).Invoke(null,new [] { myObject});

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In my code, I am creating a collection of objects which will be accessed
I'm creating some videos from a collection of images, I subsequently wish to play
I'm creating an application that will store a hierarchical collection of items in an
I am planning on creating a small website for my personal book collection. To
While creating classes in Java I often find myself creating instance-level collections that I
I'm creating a class named TetraQueue that inherits System.Collections.Generic.Queue class overriding the Dequeue method,
Prior to C# generics, everyone would code collections for their business objects by creating
I have got a python script which is creating an ODBC connection. The ODBC
I've got a function creating some XmlDocument: public string CreateOutputXmlString(ICollection<Field> fields) { XmlWriterSettings settings
Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.