LWS
LWS

Reputation: 329

Map enumareted properties to array by Automapper

Given is an class with indexed properties

    public class Foo
    {
        public int Bar1 { get; set; } = 17;
        public int Bar2 { get; set; } = 42;
        public int Bar3 { get; set; } = 99;
        ... 
                   Bar<n>
    }

result is

List of int contain 17,42,99 ...

How to configure mapper that I can consume Automapper like this

List<int> bars = mapper.Map<List<int>>(foo); 

Upvotes: 1

Views: 148

Answers (2)

Innat3
Innat3

Reputation: 3576

You can achieve this with Reflection

List<int> bars = new List<int>(foo.GetType()
                                  .GetProperties()
                                  .Where(x => x.PropertyType == typeof(int))
                                  .Select(x => (int)x.GetValue(foo)));

Or if you also need the property names to sort or filter them in some way

 Dictionary<string, int> bars = foo.GetType()
                                   .GetProperties()
                                   .Where(x => x.PropertyType == typeof(int))
                                   .ToDictionary(x => x.Name,  x => (int)x.GetValue(foo));

Upvotes: 3

Gleb
Gleb

Reputation: 1761

I agree with Innat3 on this but his answer misses few points. Here:

        var bars = foo.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.PropertyType == typeof(int))
            .Where(x => x.Name.StartsWith("Bar"))
            .Select(x => (int)x.GetValue(foo))
            .ToList();

And of course it doesn't involves Automapper as well as your indexed properties. I didn't rely on them cuz I don't know how exactly you implemented those.

Upvotes: 1

Related Questions