Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have bellow function which returns a list of dynamic object

C#
public List<dynamic> getlist()
            {
                List<dynamic> d = new List<dynamic>();
    
                d.Add(new { Name = "A", Age = 12 });
                d.Add(new { Name = "B", Age = 10 });
                d.Add(new { Name = "C", Age = 15 });
                d.Add(new { Name = "D", Age = 18 });
                d.Add(new { Name = "E", Age = 17 });
    
                return d;
    
            }

and also have a class
C#
public class testclass
        {
            public string letter { get; set; }
            public Int64 frequency { get; set; }
        }


I use AutoMapper.5.2.0 .I want to map the dynamic list with the list of **testclass** class .
can anybody give an example how to do this?

What I have tried:

..............................................................
Posted
Updated 7-Feb-17 6:28am

1 solution

Assuming you want a direct mapping from one type to the other, something like this should work:
static void CreateDynamicTestClassMap(IMapperConfigurationExpression configuration)
{
    var dynamicObject = new { Name = default(string), Age = default(int) };
    var map = configuration.CreateMap(dynamicObject.GetType(), typeof(testclass));
    map.ForMember(nameof(testclass.letter), o => o.MapFrom(nameof(dynamicObject.Name)));
    map.ForMember(nameof(testclass.frequency), o => o.MapFrom(nameof(dynamicObject.Age)));
}

...

var config = new MapperConfiguration(CreateDynamicTestClassMap);
config.AssertConfigurationIsValid();

var mapper = config.CreateMapper();
var listOfTestClass = GetList().Select(mapper.Map<testclass>).ToList();

NB: The CreateDynamicTestClassMap method will need to be in the same assembly as your GetList method, otherwise the two dynamic types will not match.
 
Share this answer
 
Comments
Karthik_Mahalingam 7-Feb-17 22:14pm    
5
Maciej Los 8-Feb-17 2:09am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900