将datatable转换为datareader

时间:2012-02-01 05:32:13

标签: c# ado.net

为了提高性能,我想将datatable转换为datareader。我不能通过查询来做到这一点。那么还有其他方法吗?

4 个答案:

答案 0 :(得分:35)

我知道这已经过时了,但这里的答案似乎已经错过了OP的问题。

DataTables有一个名为CreateDataReader的方法,它允许您将DataTable转换为DbDataReader对象。在这种情况下,DataTableReader

DataTable table = new DataTable(); 
//Fill table with data 
//table = YourGetDataMethod(); 
DataTableReader reader = table.CreateDataReader();

我应该指出,这不会提高性能,因为你应该使用其中一个。

以下是关于此事的更多资源:

答案 1 :(得分:2)

例如

public  DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();

try
{

foreach(DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow.GetType();
myDataColumn.ColumnName = myRow[0].ToString();
datatable.Columns.Add(myDataColumn);
}
while(dataReader.Read())
{
DataRow myDataRow = datatable.NewRow();
for(int i=0;i<schemaTable.Rows.Count;i++)
{
myDataRow[i] = dataReader[i].ToString();
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
return datatable;
}
catch(Exception ex)
{
Error.Log(ex.ToString());
return datatable;
}

}

答案 2 :(得分:0)

public   DataTable   GetTable(IDataReader   _reader) 
{ 
DataTable   dataTable1   =   _reader.GetSchemaTable(); 
DataTable   dataTable2   =   new   DataTable(); 
string[]   arrayList   =   new   string[dataTable1.Rows.Count]; 
for   (int   i   =   0;   i   <   dataTable1.Rows.Count;   i++) 
{ 
DataColumn   dataColumn   =   new   DataColumn(); 
if   (!dataTable2.Columns.Contains(dataTable1.Rows[i][ "ColumnName "].ToString())) 
{ 
dataColumn.ColumnName   =   dataTable1.Rows[i][ "ColumnName "].ToString(); 
dataColumn.Unique   =   Convert.ToBoolean(dataTable1.Rows[i][ "IsUnique "]); 
dataColumn.AllowDBNull   =   Convert.ToBoolean(dataTable1.Rows[i][ "AllowDBNull "]); 
dataColumn.ReadOnly   =   Convert.ToBoolean(dataTable1.Rows[i][ "IsReadOnly "]); 
dataColumn.DataType   =   (Type)dataTable1.Rows[i][ "DataType "]; 
arrayList[i]   =dataColumn.ColumnName; 
dataTable2.Columns.Add(dataColumn); 
} 
} 
dataTable2.BeginLoadData(); 
while   (_reader.Read()) 
{ 
DataRow   dataRow   =   dataTable2.NewRow(); 
for   (int   j   =   0;   j   <   arrayList.Length   ;   j++) 
{ 
dataRow[arrayList[j]]   =   _reader[arrayList[j]]; 
} 
dataTable2.Rows.Add(dataRow); 
} 
_reader.Close(); 
dataTable2.EndLoadData(); 
return   dataTable2; 
} 

答案 3 :(得分:0)

使用DataTable构造函数,

DataTable table = new DataTable(); 
//Fill table with data 
DataTableReader reader = new DataTableReader(table);

好看!