简体   繁体   中英

C# CSVhelper in record delimiters into a list

In my CSV the main files are delimited by "," which is normal. However, within some of my records they are delimited by "|", which is where the problem is.

My Model:

public class Inventory
{
    public string Year { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public string Trim { get; set; }
    public string Body { get; set; }
    public ICollection<Images> ImageURLS { get; set; }
}

public class Images
{
    public string ImageURLS { get; set; }
}

My Controller with pseudo code:

I need to read the record, if it sees a |, stop, add to the images list, skip the | and repeat until the end.

public ActionResult Inventory()
    {
        var listInventory = new List<Inventory>();
        try
        {

            var reader = new CsvReader(new StreamReader(Server.MapPath("~/9712.txt")));
            var invList = reader.GetRecords<Inventory>();

            foreach (var i in invList)
            {
                var vehicle = new Inventory();

                vehicle.Make = i.Make;

                bool split = true;

                while (split)
                {
                    read the string
                    if ("|") then stop.
                    add to vehicle.ImageURLS.Add(string);
                    skip ("|")
                } 
                listInventory.Add(vehicle);
            } 
        }
        catch
        {

        } 
        return View(listInventory);
    }

I know this is an old question, but what you need to do is create a class that inherits from CsvClassMap (as per the CsvHelper docs). In it, you'll need to create a custom converter. It should look something like:

public sealed class MappingClass : CsvClassMap<Inventory>
    {
        public MappingClass()
        {
            AutoMap();
            Map(m => m.ImageURLS).ConvertUsing(r => r.GetField("Images")
                .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => new Image{ImageURLS = x}).ToList());
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM