12

In C# & .NET, can one create a DataView that includes only a proper subset of the DataColumns of a given DataTable?

In terms of relational algebra, one assigns a RowFilter in order to perform a "selection" operation (σ). How would one perform a "projection" operation (π)?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
JaysonFix
  • 2,515
  • 9
  • 28
  • 28

4 Answers4

20

You can't do that, but you can create a copy of the table with only the columns you want :

DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "FirstColumn", "SecondColumn", "ThirdColumn");

Optionally you can return rows that have distinct values for the selected columns :

DataView view = new DataView(table);
DataTable table2 = view.ToTable(true, "FirstColumn", "SecondColumn", "ThirdColumn");
Alielson Piffer
  • 343
  • 2
  • 10
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Thank you, Thomas. I'd also like to be able to include calculated columns in "table2". For example, view.ToTable ( "FirstColumn * 2", "SecondColumn > 0", "TRIM(ThirdColumn)" ) . – JaysonFix Jul 29 '09 at 16:26
  • create them in table and select them in ToTable, or add them to table2 after you created it... – Thomas Levesque Jul 29 '09 at 17:00
  • 1
    You can shorten this by using the DefaultView of the DataTabe: `$DataTable.DefaultView.ToTable("FirstColumn", "SecondColumn", "ThirdColumn");` – Florian Feldhaus Jan 17 '15 at 09:18
  • @ThomasLevesque how do I add a condition like `FirstColumn = 'comevalue'`? – Smith Aug 18 '16 at 07:16
  • @Smith you can add it when you create the view: `new DataView(table) { RowFilter = "FirstColumn = 'somevalue'" }` (or something like that) – Thomas Levesque Aug 18 '16 at 10:14
1

Well I can't see any reason for "wanting" to do that... Remember, a DataView is just a list of pointers to the rows in the original table, and there is obviously no way to remove columns from the the original table... at least not without affecting every other function utilizing that table... Just only use the columns you want...

Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0

create dataview as a swap from one table to other table, and use the dtswap as datasource.

DataView dw = new DataView(dtfee);
            DataTable dtswap = new DataTable();
            dtswap = dw.ToTable(true,"Fees", "FeeAmount", "Year", "CollectorName", "Month");
aamir
  • 1
-1

DataSet and its associated types have no ability to perform relational operations.

John Saunders
  • 160,644
  • 26
  • 247
  • 397