我想选择DataTable中以字符' hz'开头的所有列。目前我正在这样做:
var uploadTable = dataTable.DefaultView.ToTable(false, "locID", "hz1582", "hz1581", "hz1580", "hz1579", "hz1578", "hz1577", "hz1576", "hz1575", "hz1574", "hz1573", "hz1572", "hz1571");
然而,' hz'每次运行我的代码时,列都是可变的,所以我需要一些方法来选择表中以hz开头的所有列。另请注意列' locID'总是存在,需要返回。所以,我需要这样的东西:
var uploadTable = dataTable.DefaultView.ToTable(false, "locID", "hz%");
有什么想法吗? 感谢。
答案 0 :(得分:4)
我会使用LINQ执行此任务:
DataTable uploadtable = dataTable.Copy();
var removeColumns = dataTable.Columns.Cast<DataColumn>()
.Where(c => !c.ColumnName.StartsWith("hz", StringComparison.InvariantCultureIgnoreCase));
foreach (DataColumn colToRemove in removeColumns)
uploadtable.Columns.Remove(colToRemove.ColumnName);
答案 1 :(得分:0)
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName).Where(n => n.Contains("hz")).ToArray();
var uploadTable = dataTable.DefaultView.ToTable(false, columnNames);