Filter DataTable based on Columns in C#

 I want to create another DataTable from the first DataTable but exclude some of its columns.

Usually, this can be done by creating another DataTable and manually transferring the columns and rows I need, But isn't there an easy way to do this task.

Meanwhile, an another solutions is also available that makes this easy without any manually work.

DataTable.DefaultView.ToTable(bool, Params string[] ColumnNames);
 
The above Method creates and returns a new DataTable based on rows in an existing DataView. 

You have to passes two parameters to this function.
  1. If true, the returned DataTable  contains rows that have distinct values for all its columns. The default value is false.

  2. A string array that contains a list of the column names to be included in the returned DataTable . The DataTable contains the specified columns in the order they appear within this array.

For Example:

DataTable NewTable = dt.DefaultView.ToTable(false, "StartDate", "FinishDate", "ItemName", "AssigneeNames", "ProjectName", "PercentComplete");

    

Ebook Download
View all
Learn
View all