首页 > 解决方案 > 映射通用值列表的问题

问题描述

我需要将通用键值列表映射到我的模型类。

下面是KeyValues课堂。

public class KeyValues
{
    public string Key   { get; }
    public string Value { get; set; }
}

IList<KeyValues>使用以下值将此作为输入

Key = "SystemId"
Value = "12"

Key = "SystemName"
Value = "LTPVBN21"

Key = "Location"
Value = "NJ2"

我想将此映射到我的以下SystemInformation类属性。基于 Key 需要在对应的属性中设置值。

public class SystemInformation
{
    public string SystemId   { get; set; }
    public string SystemName { get; set; }
    public string Location   { get; set; }
}

现在我正在循环IList<KeyValues> 对象并在模型中设置值比较键。

有没有其他方法可以使用 Automapper 或任何其他选项来实现这一点,因为我必须对多个模型执行类似的操作。

标签: c#.netautomapper

解决方案


为此,您需要在此处使用反射,它类似于以下内容:

SystemInformation information = new SystemInformation();
foreach(var item in values)
{
    information.GetType()
                    .GetProperty(item.Key)
                    .SetValue(information, item.Value);
}

请参阅工作演示小提琴

我正在使用专门的SystemInformation对象,但它可以是任何对象,您可以调用GetType()以获取类型详细信息,然后通过调用反射方法进一步继续。

希望能帮助到你。


推荐阅读