Using string.Split() in AutoMapper while conversion

73 views Asked by At

I have two classes A and B and I am converting class A to B, and there's one property that is a string but has two date times within one string value.

class A 
{
    public string dates { get; set; }
}

class B: A
{
    public B()
    {
        Map(m=> m.dates)
            .TypeConverter<DateTimeConverter>()
            .TypeConverterOption.Format("yyyy-MM-ddTHH:mm:ssz");
    }
}

The problem is that when I have one value in the dates, it's working perfectly, but when it's multiple values with a new line splitter, it gives the error.

  • Working Fine on 2023-01-30T01:00:00
    expected output: 2023-01-30T01:00:00z (works as expected)

  • An issue on 2023-01-30T01:00:00\r\n2023-01-30T01:00:00\r\n
    Expected output: 2023-01-30T01:00:00z\r\n2023-01-30T01:00:00z\r\n

Any solution?

1

There are 1 answers

0
EL Khayar On

you can just use linq to split your string to and, out put it in any format that you want.

class A
{
    public string dates { get; set; } 
}
class B : A
{
    public B()
    {
        Map();
    }

    private void Map()
    {
        var ss = "2017-01-11T10:27:00\r\n2011-09-04T12:30:22\r\n2020-07-17T03:51:20";
        var n = ss.Length;

        var list = new List<string>();

        var sp = ss.Split('\n');

        sp.ToList().ForEach(x => list.Add(DateTime.Parse(x).ToString("yyyy-MM-ddTHH:mm:ssz")));

        dates = string.Join("__", list.ToArray());
    }
}

if it is Windows the "\n" it is works as "\r\n" during splitting the string, the split() method takes argument type char, therefore you can not split it using two chars "\r\n" or string. if it is Mac change the "\n" with "\r".