Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map constants and class property values to a Dictionary<int, object>?

I have an class called Contact and another class called ContactKeys that contain Int32 constants. Each constant maps to a property of the Contact class and has an identical name.

public class Contact
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static class ContactKeys
{
    public const int Name = 5284;
    public const int Age = 9637;
}

Using Automapper, I need to create a Dictionary<int, object> object where the key is a constant from ContactKey, and the value is provided by the property of the same name from the Contact class.

From this post I can see that could potentially serialize the Contact class to JSON and then map it. But I don't know how to then get the constants mapped.

Any ideas?

like image 416
Digbyswift Avatar asked Dec 02 '25 06:12

Digbyswift


1 Answers

I don't know AutoMapper and why you need to use it to solve this problem but here is a solution using reflection:

Contact myContact = ...;

typeof(ContactKeys)
    .GetFields(BindingFlags.Public | BindingFlags.Static)
    .ToDictionary(f => (int)f.GetValue(null),
                  f => typeof(Contact).GetProperty(f.Name).GetValue(myContact));
like image 56
ChrisWue Avatar answered Dec 03 '25 18:12

ChrisWue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!