How to delete rows from DataTable with 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();

Method 2

Try this inline lambda code with extension methodes:

  dTable.AsEnumerable().Where(r => r.Field("col1") == "ali").ToList().ForEach(row => row.Delete());
  dTable.AcceptChanges();

Method 3

you use for loop or while loop to delete rows but not foreach

below is non linq solution

dTable= dTable.Select("col1 <> 'ali'").CopyToDataTable();

LINQ

dTable = dTable.AsEnumerable().Where(r => r.Field<string>("col1") != "ali").CopyToDataTable();

Method 4

var results = from row in dTable.Tables["tablename"].AsEnumerable()
          where row.Field<string>("Col1") == "ali" 
          select row;
foreach (DataRow row in results)
{
   dTable.Tables["tablename"].Remove(row);
}

Method 5

Try this

DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();

Method 6

I searched far and wide (well, more than four Google searches) for a solution to this and in the end I eventually gleaned (above in Sergey Berezovskiy’s post) that LINQ doesn’t do deletes – so you use LINQ to select the rows you want to get rid of and delete them through the ‘usual’ mechanism of the database technology in use. Seems to make all that database-agnostic propaganda about LINQ pretty silly?

This does work although with a little more experimentation one might be able to reduce the two ‘For Each’ loops to one.

I had a table of Properties where I wanted to delete all the entries with a chosen property name (3rd keyfield) for a particular ObjectType (1st Keyfield) and I came up with this.

FYI the REPLY object is a bit like the Error object – I just package error messages, a binary Pass/fail flag and a few other things so I can pass back loads of stuff from a query and (eventually) show the error to the user.

  ' <summary>
  ' The user has decided they don't want a particular property type so we delete all
  ' properties of that type in the table - belonging to any object of that ObjectType
  ' </summary>
  ' <param name="sObjectType"></param>
  ' <param name="sName"></param>
  ' <returns></returns>
  ' <remarks></remarks>
  Public Function DeleteAllPropsByName(sObjectType As String, sName As String) As Reply

    ' Default answer is 'OK'
    DeleteAllPropsByName = New Reply(True)

    Dim T As DataTable = mDB.DataTableImage(msTableName)
    Dim q = From rw In T.AsEnumerable
            Where rw.Field(Of String)("ObjectType") = sObjectType _
            And rw.Field(Of String)("PropName") = sName

    ' Somewhere to remember our list of target rows to delete
    Dim rows As New List(Of DataRow)

    For Each row In q
      '
      ' LINQ doesn't delete so we need to delete from the Datatable directly.
      ' If we delete here we get the collection modified error so we have to save 
      ' the datarows to ANOTHER list and then delete them from there.
      rows.Add(row)

    Next

    For Each rw As DataRow In rows
      '
      ' Call the Delete routine in my table class passing it the 
      ' primary key of the row to delete
      '
      DeleteAllPropsByName = gDB.Table(msTableName).Delete( _
                                  rw.Item("ObjectType").ToString, _
                                  CInt(rw.Item("ObjectID")), _
                                  rw.Item("PropName").ToString)

      If Not DeleteAllPropsByName.OK Then
        ' The reply object (in DeleteAllPropsByName) has all the error info so we can just
        ' exit and return it if the delete failed.
        Exit Function
      End If

    Next

  End Function

Method 7

dTable.Rows.Remove(dTable.AsEnumerable().Where(r => r.Field<string>("col1") == "Ali").FirstOrDefault());


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x