LINQtoCSV | How to write text at the end of a CSV file

Is it possible to write data at the end of the csv file or one line after the end of the csv file when using the LINQToCSV library.

I use LINQtoCSV and pass List <> to write data. my list <> looks like

x    y    z

1    4    5

1    5    3

Now I want to make y * z for each record and write the sum at the end of the csv file.

Sum = 35

I have been looking for this for a while, but have not found any solution.

+4
source share
2 answers

https://social.msdn.microsoft.com/Forums/vstudio/en-US/00c609c0-5048-4ef1-8c03-e7c6217d8a32/n-not-working-in-fileappendalltext?forum=csharpgeneral

File.AppendAllText(csvPath, ""); 

did the trick.

EDIT:

I looped all the List entries and collected the sum y * z.

sum = 0;
for (int i= 0; i < myList.Count; i++)
    sum += (y * z);

File.AppendAllText(csvPath, String.Concat("Sum = ", sum.ToString()));

To write on a single line after the end of the csv file, you can use the .NewLine environment

File.AppendAllText(csvPath, Environment.NewLine);
File.AppendAllText(csvPath, String.Concat("Sum = ", sum.ToString()));
+2

, , , - :

CsvContext csv = new CsvContext();
var models = csv.Read<CsvData>(@"c:\Icons\Windows7\Desktop\Book2.csv").ToList();
CsvData sum = new CsvData();
sum.z = models.Sum(m => m.y * m.z);
models.Add(sum);
csv.Write(models, @"c:\Icons\Windows7\Desktop\Book3.csv");

:

public class CsvData
{
    [CsvColumn(FieldIndex = 0)]
    public int x { get; set; }
    [CsvColumn(FieldIndex = 1)]
    public int y { get; set; }
    [CsvColumn(FieldIndex = 2)]
    public int z { get; set; }
}
+1

Source: https://habr.com/ru/post/1599255/


All Articles