C# 如何从数据行中获取列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/845872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get columns from a datarow?
提问by uzay95
I have a row collection (DataRow[] rows). And I want to import all rows to another DataTable (DataTable dt).
我有一个行集合(DataRow[] 行)。我想将所有行导入另一个 DataTable (DataTable dt)。
But how?
但是如何?
Code
代码
DataTable dt;
if (drs.Length>0)
{
dt = new DataTable();
foreach (DataRow row in drs)
{
dt.Columns.Add(row???????)
}
// If it possible, something like that => dt.Columns.AddRange(????????)
for(int i = 0; i < drs.Length; i++)
{
dt.ImportRow(drs[i]);
}
}
采纳答案by Marc Gravell
Assuming the rows all have the same structure, the easiest option is to clone the old table, omitting the data:
假设所有行都具有相同的结构,最简单的选择是克隆旧表,省略数据:
DataTable dt = drs[0].Table.Clone();
Alternatively, something like:
或者,类似于:
foreach(DataColumn col in drs[0].Table.Columns)
{
dt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
}
回答by Alan McBee - MSFT
How about
怎么样
DataTable dt = new DataTable;
foreach(DataRow dr in drs)
{
dt.ImportRow(dr);
}
Note this only works if drs
is a DataRowCollection
. Detached rows (not in a DataRowCollection
are ignored).
请注意,这仅适用drs
于DataRowCollection
. 分离的行(不在 aDataRowCollection
中的行被忽略)。
Don't forget to call AcceptChanges.
不要忘记调用 AcceptChanges。
回答by Sathish Naga
If your DataRows is from a Data Table with Columns defined in it,
如果您的 DataRows 来自其中定义了列的数据表,
DataRow[] rows;
DataTable table = new DataTable();
var columns = rows[0].Table.Columns;
table.Columns.AddRange(columns.Cast<DataColumn>().ToArray());
foreach (var row in rows)
{
table.Rows.Add(row.ItemArray);
}