I have the following code to delete rows from DataTable:
var rows = dTable.Select("col1 ='ali'");
foreach (var row in rows)
row.Delete();
above code work fine. how to convert this code to LINQ?
You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands.
When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data source, use the Delete method of the DataRow to remove the row. The Delete method marks the row as Deleted in the DataSet or DataTable but does not remove it.
LINQ is not for deleting or modifying - it is for querying data. With LINQ you can select data which should be deleted, and then delete those data manually (e.g. in foreach loop or with ForEach list extension):
var query = dTable.AsEnumerable().Where(r => r.Field<string>("col1") == "ali");
foreach(var row in query.ToList())
row.Delete();
UPDATE: Also with LINQ to DataSet you can select all rows which should stay in table and create new DataTable from those rows:
var table = dTable.AsEnumerable()
.Where(r => r.Field<string>("col1") != "ali")
.CopyToDataTable();
Try this inline lambda code with extension methodes:
dTable.AsEnumerable().Where(r => r.Field("col1") == "ali").ToList().ForEach(row => row.Delete()); dTable.AcceptChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With