7

I would like to select all columns in a DataTable that begin with the characters 'hz'. At the moment I am doing this:

var uploadTable = dataTable.DefaultView.ToTable(false, "locID", "hz1582", "hz1581", "hz1580", "hz1579", "hz1578", "hz1577", "hz1576", "hz1575", "hz1574", "hz1573", "hz1572", "hz1571");

However, the 'hz' columns are variable each time I run my code, so I need some way of selecting all columns in the table that begin with hz. Note also that the column 'locID' is always present and needs to be returned. So, I need something like this:

var uploadTable = dataTable.DefaultView.ToTable(false, "locID", "hz%");

Any ideas? Thanks.

2
  • What means you need to select the columns? You need to select the rows which column-names start with hz? Or you need to select only the DataColumns without data? Commented Mar 8, 2017 at 10:04
  • I need to select the rows as well. i.e. subset the datatable based on the coluumn names. Commented Mar 8, 2017 at 10:07

2 Answers 2

9

I would use LINQ for this task:

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this looks like just what I need!
1
 string[] columnNames = dt.Columns.Cast<DataColumn>()
                                         .Select(x => x.ColumnName).Where(n => n.Contains("hz")).ToArray();

    var uploadTable = dataTable.DefaultView.ToTable(false, columnNames);

4 Comments

you linq will not work for Machzor column name?
@J.SMTBCJ15 why?
because @azar he said start with not contains and if column name is Machzor will be considered as column which is not actually
@J.SMTBCJ15 Yes Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.