Create ADO.NET DataView showing only selected Columns
Solution 1
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");
Solution 2
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...
JaysonFix
Updated on June 05, 2022Comments
-
JaysonFix almost 2 years
In C# & .NET, can one create a
DataView
that includes only a proper subset of theDataColumn
s of a givenDataTable
?In terms of relational algebra, one assigns a
RowFilter
in order to perform a "selection" operation (σ). How would one perform a "projection" operation (π)? -
JaysonFix almost 15 yearsThank 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)" ) .
-
Thomas Levesque almost 15 yearscreate them in table and select them in ToTable, or add them to table2 after you created it...
-
Florian Feldhaus over 9 yearsYou can shorten this by using the DefaultView of the DataTabe:
$DataTable.DefaultView.ToTable("FirstColumn", "SecondColumn", "ThirdColumn");
-
Smith over 7 years@ThomasLevesque how do I add a condition like
FirstColumn = 'comevalue'
? -
Thomas Levesque over 7 years@Smith you can add it when you create the view:
new DataView(table) { RowFilter = "FirstColumn = 'somevalue'" }
(or something like that)