Reputation: 151
I am using one object list type where it read data from datareader and add in the list. Below is the code for the same:
public static List<object[]> LoadRecordsFromDataReaderToList(SqlDataReader reader, int dataLimit)
{
List<object[]> dataList = new List<object[]>();
while (reader.Read())
{
object[] columnName = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
columnName[i] = reader.GetName(i);
}
dataList = new List<object[]>{columnName};
object[] tempRow = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
tempRow[i] = reader[i];
}
dataList.Add(tempRow);
}
return dataList;
}
As you can see in above code first running one for loop to get all the columns and assign in list like below image. List with column name image
Then running one more loop to get the value and trying to assign for the same column name but after added tempRow list is showing two items count, First items with all the column names and second items with all the values. Below is the image added for all the values. List with added values
How do i assign value for the specific column index in list? Please let me know if you have any concerns.
Upvotes: 0
Views: 377
Reputation: 460168
It seems you want to add the column-names as "header" once and not always in the while-loop. You are always overwriting the whole list in the record-loop at:
dataList = new List<object[]>{columnName};
I think you can use this approach:
public static List<object[]> LoadRecordsFromDataReaderToList(SqlDataReader reader)
{
List<object[]> dataList = new List<object[]>();
if (reader.HasRows)
{
// add header first and just once
string[] columns = Enumerable.Range(0, reader.FieldCount)
.Select(reader.GetName)
.ToArray();
dataList.Add(columns);
}
while (reader.Read())
{
// add data records
object[] tempRow = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
tempRow[i] = reader[i];
}
dataList.Add(tempRow);
}
return dataList;
}
Upvotes: 1