Search code examples
c#.netcsvhelper

How to parsegju,jk


I have to parse a TSV file which has the following structure: [Secti "1 2" "2 3"his?


Solution

  • I'm not sure if this is what you were trying to do or not. I also noticed that it appeared to be 4 spaces between records. If it is actually a tab, you can change the delimiter to a tab Delimiter = "\t",

    void Main()
    {
        var data = @"[Section one of info]
    ""Atr1    1""
    ""Atr2    2""
    [Section two of info]
    ""Atr3    Atr4""
    ""1    2""
    ""2    3""
    ""4    5""";
    
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            Delimiter = "    ",
            Mode = CsvMode.Escape
        };
    
        using (var reader = new StringReader(data))
        using (var csv = new CsvReader(reader, config))
        {
            var isSectionOne = true;
            var record = new Foo() { Atr3 = new List<int>(), Atr4 = new List<int>() };
            
            while(csv.Read())
            {
                if (csv.GetField(0).StartsWith("["))
                    continue;
                    
                if (isSectionOne)
                {
                    if (csv.GetField(0) == "Atr1")
                    {
                        record.Atr1 = csv.GetField<int>(1);
                    }
                    if (csv.GetField(0) == "Atr2")
                    {
                        record.Atr2 = csv.GetField<int>(1);
                    }
                    if (csv.GetField(0) == "Atr3")
                    {
                        isSectionOne = false;
                    }
                }
                else
                {
                    record.Atr3.Add(csv.GetField<int>(0));
                    record.Atr4.Add(csv.GetField<int>(1));
                }           
            }
            record.Dump();
        }
    }
    
    public class Foo
    {
        public int Atr1 { get; set; }
        public int Atr2 { get; set; }
        public List<int> Atr3 { get; set; }
        public List<int> Atr4 { get; set; }
    }