CsvHelper - Read different record types in same CSV

前端 未结 2 1465
忘了有多久
忘了有多久 2021-01-27 13:46

I\'m trying to read two types of records out of a CSV file with the following structure:

PlaceName,Longitude,Latitude,El         


        
2条回答
  •  执念已碎
    2021-01-27 14:38

    I got a response from Josh Close on the issue tracker:

    CsvReader not recognising different registered class maps

    Here is his answer to this question:

    Since you don't have a single header, you'll need to ignore headers and use indexes instead. This brings up an idea though. I could have the ReadHeader method parse headers for a specific record type.

    Here is an example that should work for you though.

    void Main()
    {
        LocationDefinition Location;
        var Counts = new List();
    
        using (var stream = new MemoryStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        using (var csvReader = new CsvReader(reader))
        {
            writer.WriteLine("PlaceName,Longitude,Latitude,Elevation");
            writer.WriteLine("NameString,123.456,56.78,40");
            writer.WriteLine();
            writer.WriteLine("Date,Count");
            writer.WriteLine("1/1/2012,1");
            writer.WriteLine("2/1/2012,3");
            writer.WriteLine("3/1/2012,10");
            writer.WriteLine("4/2/2012,6");
            writer.Flush();
            stream.Position = 0;
    
            csvReader.Configuration.HasHeaderRecord = false;
            csvReader.Configuration.RegisterClassMap();
            csvReader.Configuration.RegisterClassMap();
    
            csvReader.Read(); // get header
            csvReader.Read(); // get first record
            var locationData = csvReader.GetRecord();
    
            csvReader.Read(); // skip blank line
            csvReader.Read(); // skip second header section
    
            // Read count data records
            while (csvReader.Read())
            {
                var tempCount = csvReader.GetRecord();         
                Counts.Add(tempCount);
            }
        }
    }
    
    public class LocationDefinition
    {
        public string PlaceName { get; set; }
        public double Longitude { get; set; }
        public double Latitude { get; set; }
        public double Elevation { get; set; }
    }
    
    public sealed class LocationMap : CsvClassMap
    {
        public LocationMap()
        {
            Map(m => m.PlaceName);
            Map(m => m.Longitude);
            Map(m => m.Latitude);
            Map(m => m.Elevation);
        }
    }
    
    public class CountDefinition
    {
        public DateTime Date { get; set; }
        public int Count { get; set; }
    }
    
    public sealed class CountMap : CsvClassMap
    {
        public CountMap()
        {
            Map(m => m.Date);
            Map(m => m.Count);
        }
    }
    

提交回复
热议问题