Stack Overflow Asked by irham dollah on December 23, 2021
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 ?
The class Record should be the problem.
GetSum()
is a function and functions will be not serialized.
x
and y
are properties (as you can indicate on { get; set; }) and will be serialized.
You can change the function to a property like that:
public int GetSum
{
get
{
return _x+_y;
}
}
The next problem will be that the _x
and _y
variables are never set to a value. So GetSum
will always return 0.
Answered by ChemCode on December 23, 2021
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);
Answered by Caius Jard on December 23, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP