Let’s say I have a table with a Color column. Color can have various values. I have a C# method that can handle items of a given column at a time. Thus, I would like to :
foreach(colorname in mytable.getDistinctColornames)
monocolorMethod(mytable.getSubTableOnlyContainingRowsWithColor(colorname))
How would I do that elegantly … ?
At all prices, I would avoid copying the data back & forth. I would like kind of a view on the datatable. A view that would only “show” the rows of a given columns, and a “writable” view (i.e. when I write to the filtered subset, the original table is written to)
EDIT :
Let’s say I have a ‘Car’ Table, and I would like to replace ‘Sedan’ by ‘Truck’ in column ‘Type’ for all cars with ‘Color=Red’.
How would I do given the following code ?
DataTable cars (...); // the data
DataView dv = cars.DefaultView;
dv.RowFilter = "Color='Red'";
< Here I would like to loop on the DataView>. The following code does not work :
foreach (row in dv.AsEnumerable)
{
if(row["Type"] == "Sedan")
row["Type"] = "Truck";
}
EDIT 2 :
Found this http://msdn.microsoft.com/fr-fr/library/system.data.dataview.allowedit.aspx which suggests
view.AllowEdit = true;
view[0].BeginEdit();
view[0]["FirstName"] = "Mary";
view[0]["LastName"] = "Jones";
view[0].EndEdit();
Did you try using
DataViewclass? It looks like exactly what you want to achieve without using LINQ: http://msdn.microsoft.com/en-us/library/fdcwwhezAn example of usage:
Let say there is a
DataTableobject named_dtwith 4 rows in it:You can easily create DataView which doesn’t filter data but perform sorting operation on it:
You can also add new rows into the
DataViewand because it is set on correspondingDataTablethat new row will be added directly to_dtobject. The sorting order will be updated as well, and new row won’t be the last one within theDataView(because sort is done on Order and Name columns)After that code there will be 5 rows in
_dt. Editing rows is also quite simple:You can also use
DataView.Find()orDataView.FindRows()methods to find a row within theDataView.