c# - 使用自动映射器将名称/值对映射到对象的列表

标签 c# .net-core automapper

所以我有一个包含单元格列表的行列表,每个单元格都是一个字符串和对象:

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/

相关文章:

c# - 使用linq和automapper在dto中将属性序列化为复杂类型

c# - AutoMapper 自动创建 createMap

c# - Mono 上的跨平台高分辨率滴答计数器?

c# - 保存文件 - xmlSerializer

c# - 如何创建.net core类库

c# - 在 .NET 4.8 中引用 .NET Core 3.0 库?

c# - 当指定条件 != null 时,Automapper 未正确映射 null 列表成员

c# - 仅使用扩展方法在 Linq 中进行漂亮、干净的交叉连接

c# - 在 C# 中的两个日期之间迭代

c# - 重复调用HashCode.Combine