【问题标题】:How to map dictionary with values containg tuples to class instance如何将包含元组的值的字典映射到类实例
【发布时间】:2020-07-29 19:46:35
【问题描述】:

我有一本 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),但我可以用一个类来替换它。所以,元组或类都没有关系,我只需要为每个字典项设置三个属性(IdCodeName)。

我需要将这个字典投影到一个类中,所以我像这样分别映射输出模型的每个属性:

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

我想知道有没有其他(更花哨的)方法来做同样的映射?

【问题讨论】:

标签: c# dictionary tuples mapping


【解决方案1】:

您可以执行以下操作。

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

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2022-12-07
    • 2019-05-09
    相关资源
    最近更新 更多