.NET-将列表转换/映射为对象,反之亦然 [英] .NET - Convert/map list into object and vis versa
问题描述
我有以下列表,其中包含字段名称和值.
I have the following list which contains field names and values.
public class FormField
{
public string FieldName { get; set;}
public string FieldValue { get; set;}
}
var formData = new List<FormField>();
formData.Add(new FormField { FieldName = "Date", FieldValue = "2017-09-14" });
formData.Add(new FormField { FieldName = "Name", FieldValue = "Job blogs" });
formData.Add(new FormField { FieldName = "IsEnabled", FieldValue = "true" });
如何将列表转换或映射到以下类?注意FieldNames映射到该类的属性.
How can I convert or map the list into the following class? Note FieldNames map to the properties of the class.
public class MyViewModel
{
[Required]
public DateTime Date { get; set; } = DateTime.now;
[Required]
public string Name { get; set; }
public boolean IsEnabled { get; set; }
public IEnumerable<SelectListItem> Titles
{
get
{
var options = new List<SelectListItem>
{
new SelectListItem(){ Value = "Mr", Text = "Mr" },
new SelectListItem(){ Value = "Mrs", Text = "Mrs" }
};
return options;
}
}
}
任何帮助表示赞赏.我是否需要以某种方式序列化列表? automapper可以这样做吗?
Any help appreciated. Do I need to serialize the list somehow? Can automapper do this?
*更新*
我尝试了以下操作,但是尽管automapper文档指出您可以直接从字典访问对象,但它还是不起作用:
I tried the following but it doesnt work despite the automapper docs stating that you can go directly from dictionary to object:
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Dictionary<string, object>, MyViewModel>();
}
}
var viewModel = Mapper.Map<MyViewModel>(formData.ToDictionary(x => x.FieldName, x => (object) x.FieldValue))
注意:我使用automapper v 5.0.2进行记录
Note: for the record I'm using automapper v 5.0.2
我还需要从对象回到字典,但是能够排除诸如public IEnumerable<SelectListItem> Titles {get;}
I also need to go back from object to dictionary but be able to exclude properties such as public IEnumerable<SelectListItem> Titles {get;}
推荐答案
您可以使用反射来获取和设置模型中的匹配属性
You could use reflection to get and set the matching properties in the model
var formData = new List<FormField>();
formData.Add(new FormField { FieldName = "Date", FieldValue = "2017-09-14" });
formData.Add(new FormField { FieldName = "Name", FieldValue = "Job blogs" });
formData.Add(new FormField { FieldName = "IsEnabled", FieldValue = "true" });
// Initialize a new instance of the model
MyViewmodel model = new MyViewmodel();
// Get its property info
PropertyInfo[] properties = model.GetType().GetProperties();
// Loop through your form field data
foreach(var field in formData)
{
// Get the matching property name
PropertyInfo pi = properties.FirstOrDefault(x => x.Name == field.FieldName);
if (pi == null)
{
continue;
}
// Convert the value to match the property type
object value = Convert.ChangeType(field.FieldValue, pi.PropertyType);
// Set the value of the property
pi.SetValue(model, value);
}
这篇关于.NET-将列表转换/映射为对象,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!