Dmitry Stepanov
Dmitry Stepanov

Reputation: 2914

How to map dictionary with values containg tuples to class instance

I have a dictionary of type Dictionary<string, (int Id, string Code, string Name)>:

var dict = new Dictionary<string, (int Id, string Code, string Name)>
{
    ["subjectType"] = (1, "1Code", "1Name"),
    ["residentType"] = (2, "2Code", "2Name"),
    ["businessType"] = (3, "3Code", "3Name"),
    // and so on...
};

I use tuple (int Id, string Code, string Name) here but I can replace it with a class. So, it doesn't matter tuple or class, I just need to have three properties (Id, Code, Name) for each dictionary item.

I need to project this dictionary into a class, so I map each property of output model separately like this:

public static OutputModel Map(
    Dictionary<string, (int Id, string Code, string Name)> dictionary) =>
        new OutputModel
        {
            SubjectTypeId = dictionary["subjectType"].Id,
            SubjectTypeCode = dictionary["subjectType"].Code,
            SubjectTypeName = dictionary["subjectType"].Name,

            ResidentTypeId = dictionary["residentType"].Id,
            ResidentTypeCode = dictionary["residentType"].Code,
            ResidentTypeName = dictionary["residentType"].Name,

            BusinessTypeId = dictionary["businessType"].Id,
            BusinessTypeCode = dictionary["businessType"].Code,
            BusinessTypeName = dictionary["businessType"].Name,

            // and so on...
        };

I wonder is there any other (more fancy) way to do the same mapping?

Upvotes: 0

Views: 78

Answers (1)

Rand Random
Rand Random

Reputation: 7440

You could do the following.

var outPutModel = new OutputModel();
foreach (var keyValuePair in dictionary)
     outPutModel.Write(keyValuePair);

public class OutputModel
{
     public void Write(KeyValuePair<string, (int Id, string Code, string Name)> keyValuePair)
     {
           var type = typeof(OutputModel);
           type.GetProperty(keyValuePair.Key + "Id", BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public).SetValue(this, keyValuePair.Value.Id);
           type.GetProperty(keyValuePair.Key + "Code", BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public).SetValue(this, keyValuePair.Value.Code);
           type.GetProperty(keyValuePair.Key + "Name", BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public).SetValue(this, keyValuePair.Value.Name);
     }
}

See it in action:

https://dotnetfiddle.net/jfKYsG

Upvotes: 1

Related Questions