所以我有一个包含单元格列表的行列表,每个单元格都是一个字符串和对象:
public List<Row> Rows { get; set; }
public class Row
{
public int Id { get; set; }
public List<Cell> Cells { get; set; }
}
public class Cell
{
public string Name { get; set; }
public object Value { get; set; }
}
这是一个内容示例:
{
new Row
{
Id = 0,
Cells = new List<Cell>()
{
new Cell { Name = "prop1", Value = "somevalue1" },
new Cell { Name = "prop2", Value = "somevalue2" },
new Cell { Name = "prop3", Value = 3 },
new Cell { Name = "prop4", Value = "24-09-2019 12:27:04" }
}
},
new Row
{
Id = 0,
Cells = new List<Cell>()
{
new Cell { Name = "prop1", Value = "somevalue3" },
new Cell { Name = "prop2", Value = "somevalue4" },
new Cell { Name = "prop3", Value = 3 },
new Cell { Name = "prop4", Value = "24-09-2019 12:27:04" }
}
}
};
我想将它映射到一个对象:
public class CustomObj
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public int prop3 { get; set; }
public DateTime? prop4 { get; set; }
}
但这在 Automapper 中如何实现呢? 我通过将单元格列表转换为字典然后使用自动映射器来工作,但它在转换日期时间时失败了。 我当前的实现是通过使用 GetProperty() 工作的,但如果我可以使用 automapper 做同样的事情,那就太好了。
最佳答案
如果没有 Automapper,它可能会非常简单。
public static CustomRow ToCustomRow(this row)
{
var values = row.Cells.ToDictionary(cell => cell.Name);
int.TryParse(values.GetValueOrDefault("prop3"), out var prop3);
DateTime.TryParse(values.GetValueOrDefault("prop4"), out var prop4);
return new CustomRow
{
prop1 = values.GetValueOrDefault("prop1"),
prop2 = values.GetValueOrDefault("prop2"),
prop3 = prop3,
prop4 = prop4
}
Automapper 的目的是减少简单映射的输入量,更复杂的情况手动编写会更快更容易理解。
关于c# - 使用自动映射器将名称/值对映射到对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58186469/