Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing list to CSV file

Tags:

c#

csv

I have a List of List of int called NN which i would like to write to a csv file like this:

List<List<int>> NN = new List<List<int>>();

The NN list:

1,2,3,4,5,6
2,5,6,3,1,0
0,9,2,6,7,8

And the output csv file should look like this:

1,2,0
2,5,9
3,6,2
4,3,6
5,1,7
6,0,8

What is the best way to achieve that?

If there is a better representation you would recommend instead of the nested list i'll be glad to know.

(The purpose is that each list of int is the weights between the last and next layer in the neural network).

like image 464
Yogevnn Avatar asked May 28 '16 12:05

Yogevnn


People also ask

How do I make a list into a CSV file?

The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.

How do I write a list to pandas csv?

CSV: Import the csv module in Python, create a csv writer object, and write the list of lists to the file in using the writerows() method on the writer object. What is this? Pandas: Import the pandas library, create a Pandas DataFrame, and write the DataFrame to a file using the DataFrame method DataFrame.

How do I write to a CSV file in Python?

DictWriter() class can be used to write to a CSV file from a Python dictionary. Here, file - CSV file where we want to write to. fieldnames - a list object which should contain the column headers specifying the order in which data should be written in the CSV file.


1 Answers

Here is how you can do it:

List<List<int>> NN = new List <List<int>>
{
    new List<int> {1,2,3,4,5,6},
    new List<int> {2,5,6,3,1,0},
    new List<int> {0,9,2,6,7,8}
};

//Get expected number of rows
var numberOfRows = NN[0].Count; 

var rows =
    Enumerable.Range(0, numberOfRows) //For each row
    .Select(row => NN.Select(list => list[row]).ToList()) //Get row data from all columns
    .ToList();

StringBuilder sb = new StringBuilder();

foreach (var row in rows)
{
    sb.AppendLine(string.Join(",", row));
}

var result = sb.ToString();
like image 198
Yacoub Massad Avatar answered Sep 21 '22 02:09

Yacoub Massad