C# Query using Npgsql for Postgresql shows duplicate results and missing table data C# Query using Npgsql for Postgresql shows duplicate results and missing table data database database

C# Query using Npgsql for Postgresql shows duplicate results and missing table data


The problem of duplicate content is caused by the loop using While(dRead.Read()) and the loop over the DataRows of the table using the foreach. This effectively loops two times on your data.

If you want to use a DataReader to loop over the records then you don't need a DataRow and a DataTable, but use the FieldCount property of the DataReader and the DataReader indexer for the current record.

// Not needed// ad.Fill(dt);NpgsqlDataReader dRead = com.ExecuteReader();while (dRead.Read()){   for(int i = 0; i < dRead.FieldCount; i++)       Console.Write("{0} \t \n", dRead[i].ToString());}

instead if you want to loop over a DataTable and its rows you need to loop using the Columns.Count

ad.Fill(dt);// Not needed// NpgsqlDataReader dRead = com.ExecuteReader();foreach(DataRow row in dt.Rows){    for (int i = 0; i < dt.Columns.Count; i++)    {        Console.Write("{0} \t \n", row[i].ToString());    }}


In your initial approach for every row you are displaying its columns up to column with index = row count. I believe that is not what you wanted to do. You should display every column per row like:

Instead of

foreach(DataRow row in dt.Rows){    for (int i = 0; i < dt.Rows.Count; i++)    {        Console.Write("{0} \t \n", row[i].ToString());    }}

Use:

foreach(DataRow row in dt.Rows){    for (int i = 0; i < row.ItemArray.Length; i++)    {        Console.Write("{0} \t \n", row.ItemArray[i].ToString());    }}