简体   繁体   中英

How add list<object> with NpgsqlDataReader() C#

I do not know what I am doing wrong, when I add the values ​​from my database to a list<object> it always returns the list with the total of objects but all the values ​​are those of the last record that was made in the loop while .

This is my code:

public List<object> getdata(string storedProcedure)
    {
        List<object> list = new List<object>();
        try
        {
            using (var conn = new NpgsqlConnection(connstring))
            {
                conn.Open();
                NpgsqlTransaction tran = conn.BeginTransaction();
                NpgsqlDataReader reader;
                var cmd = new NpgsqlCommand(storedProcedure, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                reader = cmd.ExecuteReader();

                int fieldCount = reader.FieldCount;
                object[] fieldValues = new object[fieldCount];
                while (reader.Read())
                {
                    int instances = reader.GetValues(fieldValues);
                    for (int fieldCounter = 0; fieldCounter < fieldCount; fieldCounter++)
                    {
                        if (Convert.IsDBNull(fieldValues[fieldCounter]))
                            fieldValues[fieldCounter] = "NA";                               
                    }
                    list.Add(fieldValues);
                }                       
                reader.Close();                    
                tran.Commit();
                conn.Close();
                return list;
            }
        }
        catch (Exception ex)
        {
        }
        return list;
    }

This is what I get in all positions, it is the last value: 在此处输入图片说明

You need to move the declaration and initialization of your object array inside the loop

  ....
  while (reader.Read())
  {
      object[] fieldValues = new object[fieldCount];
      ....
  }

The problem that you experience is caused by the fact that when you initialize the array outside the loop and reuse it at every loop of the datareader, you replace the previous content with the content of the current record.
But when you add the array to the list of objects you add the same reference to initial array where only the content has been changed. Obviously when you reach the last record there is only one array while the list contains n reference to the same memory area. So you display n time the same last record.

Moving the initialization inside the loop provides the list with a new reference at each loop and each reference maintain the data of the record received during the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM