Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete rows from DataTable with LINQ?

Tags:

c#

asp.net

linq

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?

like image 740
Samiey Mehdi Avatar asked Sep 17 '13 15:09

Samiey Mehdi


People also ask

How to remove row in 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.

How do I delete a row in a DataSet?

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.


2 Answers

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();
like image 199
Sergey Berezovskiy Avatar answered Oct 07 '22 21:10

Sergey Berezovskiy


Try this inline lambda code with extension methodes:

  dTable.AsEnumerable().Where(r => r.Field("col1") == "ali").ToList().ForEach(row => row.Delete());
  dTable.AcceptChanges();
like image 43
Mohamed Salemyan Avatar answered Oct 07 '22 20:10

Mohamed Salemyan