C# How to Build a Custom Dataview from a Datatable?
I Need to Create a Dataview from a Datatable, but with an Unusual Twist: I Need to Decide (With Code) on a Row-by-Row Basis Which Rows in the Datatable Are...
I need to create a DataView from a DataTable, but with an unusual twist:
I need to decide (with code) on a row-by-row basis which rows in the DataTable are included in the DataView.
DataTable dt = LoadData();
DataView dv = new DataView(dt);
foreach (DataRow row in dt.Rows)
{
if (RowIsGood(row))
{
// This obviously doesn't work but I need equivalent logic:
DataRowView drv = new DataRowView();
drv.Row = row;
dv.Add(drv);
}
}
Some important things to note:
- The code in the RowIsGood function above is too complicated to replicate using the standard RowFilter method.
- The DataTable has the potential to be very large. It is also referenced by multiple grid controls. Adding temporary columns to the DataTable to facilitate a RowFilter operation is not possible.
- I'm using .NET v4.0.
Is then even possible with the DataTable/DataView architecture?
Does LINQ allow me to customize a DataView like I need?
Thanks in advance!
2 Answers
Since you are looking for a row by row solution and already have a function that takes a DataRow and returns a bool.
Simply add the refernce to System.Data.DataSetExtensions
And use the AsDataView Method
DataView dv=DT.AsEnumerable().Where(RowIsGood).AsDataView();
DataView dv = (from n in DT.AsEnumerable() Where RowIsGood(n) select n ).AsDataView();