params (version 1)
You can use the same trick the Rows.Add
method uses namely the params
keyword
By using the params keyword, you can specify a method parameter that takes a variable number of arguments.
and pass columns names as the last parameters. Then you read the values form the reader with some LINQ and turn it into an array because it's just that, an array (but one that is created dynamically if each value is passed separately). Besides you don't need two if
s, use the and &&
operator instead.
public void FillColumns(
DataTable table,
OracleDataReader reader,
params string[] columnNames)
{
if (reader != null && reader.HasRows)
{
table.Rows.Clear();
while (reader.Read())
{
table.Rows.Add(columnNames.Select(name => reader[name]).ToArray());
}
}
}
Example call:
.FillColumns(table, reader, "Column1", "Column2");
table.Columns (version 2)
the second approach would be to read the column names from the data table
public void FillColumns(DataTable table, OracleDataReader reader)
{
if (reader != null && reader.HasRows)
{
table.Rows.Clear();
while (reader.Read())
{
table.Rows.Add(
table
.Columns
.Cast<DataColumn>()
.Select(column => reader[column.ColumnName])
.ToArray());
}
}
}
table.Load (version 3)
and the third to just load the datatable from the reader:
public void FillColumns(DataTable table, OracleDataReader reader)
{
if (reader != null && reader.HasRows)
{
table.Rows.Clear();
table.Load(reader);
}
}