Как отобразить словарь со значениями, связывающими кортежи, с экземпляром класса - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть словарь типа 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...
};

Я использую здесь кортеж (int Id, string Code, string Name), но я могу заменить его классом. Итак, не имеет значения кортеж или класс, мне просто нужно иметь три свойства (Id, Code, Name) для каждого элемента словаря.

Мне нужно спроецировать этот словарь в класс, поэтому я сопоставляю каждое свойство выходной модели отдельно, как это:

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...
        };

Интересно, есть ли другой (более изощренный) способ сделать то же самое отображение?

1 Ответ

1 голос
/ 16 апреля 2020

Вы можете сделать следующее.

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);
     }
}

Посмотреть это в действии:

https://dotnetfiddle.net/jfKYsG

...