Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get column names to print in this C# program?

I've cobbled together a C# program that takes a .csv file and writes it to a DataTable. Using this program, I can loop through each row of the DataTable and print out the information contained in the row. The console output looks like this:

--- Row --- Item: 1 Item: 545 Item: 507 Item: 484 Item: 501 

I'd like to print the column name beside each value, as well, so that it looks like this:

--- Row --- Item: 1   Hour Item: 545 Day1 KW Item: 507 Day2 KW Item: 484 Day3 KW Item: 501 Day4 KW 

Can someone look at my code and tell me what I can add so that the column names will print? I am very new to C#, so please forgive me if I've overlooked something.

Here is my code:

// Write load_forecast data to datatable. DataTable loadDT = new DataTable(); StreamReader sr = new StreamReader(@"c:\load_forecast.csv");                        string[] headers = sr.ReadLine().Split(','); foreach (string header in headers) {     loadDT.Columns.Add(header); // I've added the column headers here. }  while (sr.Peek() > 0) {     DataRow loadDR = loadDT.NewRow();     loadDR.ItemArray = sr.ReadLine().Split(',');     loadDT.Rows.Add(loadDR); }  foreach (DataRow row in loadDT.Rows) {     Console.WriteLine("--- Row ---");     foreach (var item in row.ItemArray)     {         Console.Write("Item:");         Console.WriteLine(item); // Can I add something here to also print the column names?     } } 
like image 527
Kevin Avatar asked Apr 01 '10 03:04

Kevin


People also ask

How do I print Dataframe column names?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe.

How do you do columns in C?

Each column is color-coded so you can see that column one is 7 characters wide, column two is 11 characters wide, and column three is 10 characters wide. The code to generate this would look like: printf("Column1 Column2 Column3\n"); printf("%7d%11d%10d\n", 100, 1221, 9348);

How do I get the column names of a table in SQL?

In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .

How can I see the column names in Pandas?

You can get the column names from pandas DataFrame using df. columns. values , and pass this to python list() function to get it as list, once you have the data you can print it using print() statement.


1 Answers

You need to loop over loadDT.Columns, like this:

foreach (DataColumn column in loadDT.Columns) {     Console.Write("Item: ");     Console.Write(column.ColumnName);     Console.Write(" ");     Console.WriteLine(row[column]); } 
like image 160
SLaks Avatar answered Oct 23 '22 22:10

SLaks