Search code examples
c#.netcsvread-writecsvreader

Read from .csv, calculate, write on .csv


I am using csv reader for c#. This is my Record class

internal class Record
{
    int _y;
    int _x;
    [Name("y")]
    public int y { get; set; }
    [Name("x")]
    public int x { get; set; }
    
    public int getSum()
    {
        return _x+_y;
    }
}

Then, I try to read multiple .csv files and write aggregate to 1 .csv file

using (var writer = new StreamWriter(SaveTxt.Text))
            using (var csvOut = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                for (int i = 0; i < Int16.Parse(numberFile); i++)
                {
                    using (var reader = new StreamReader(files[i]))
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        var records = csv.GetRecords<Record>();
                        csvOut.WriteRecords(records);
                        
                    }
                }
            }

But the result only show x and y data. Without showing result from getSum() function. What should I do to be able to manipulate the data that I read from .csv before write to other .csv ?


Solution

  • I believe that CsvReader is writing X and Y because they are properties; it won't call methods and include their result in the file. Convert the getSum method to a property instead and it should appear in the file. You might also have to give it a name attribute. Here's a fixed up Record class:

    internal class Record
    {
        
        
        [Name("y")]
        public int X { get; set; }
        [Name("x")]
        public int Y { get; set; }
    
        [Optional]
        [Name("sum")]
        public int Sum { get { return X + Y; } set; } }
    }
    

    (Note that in c# we write properties and method names starting with a capital letter..)

    I removed your _x and _y because they weren't doing anything; they weren't wired up to the x and y properties and would have always had their default value 0, so using them for sum would be 0 too


    You ask how to manipulate the data before writing it; out some code between these two lines:

    var records = csv.GetRecords<Record>();
    
    //put code here
    
    csvOut.WriteRecords(records);