Answers:
试试这个(LINQ方法语法):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
或使用LINQ查询语法:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
是必需的,因为Columns的类型为DataColumnCollection IEnumerable
,而不是IEnumerable<DataColumn>
。其他部分应该很明显。
string[] columnNames = dt.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "ABC").Select(x => x.ColumnName).ToArray();
用
var arrayNames = (from DataColumn x in dt.Columns
select x.ColumnName).ToArray();
我建议使用这样的扩展方法:
public static class DataColumnCollectionExtensions
{
public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
{
return source.Cast<DataColumn>();
}
}
因此:
string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();
您还可以为类实现另一种扩展方法,DataTable
以减少代码:
public static class DataTableExtensions
{
public static IEnumerable<DataColumn> GetColumns(this DataTable source)
{
return source.Columns.AsEnumerable();
}
}
并按如下所示使用它:
string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();