C# 如何使用 LINQ 从 DataTable 中删除行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18854395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:25:39  来源:igfitidea点击:

How to delete rows from DataTable with LINQ?

c#asp.netlinq

提问by Samiey Mehdi

I have the following code to delete rows from DataTable:

我有以下代码可以从 DataTable 中删除行:

var rows = dTable.Select("col1 ='ali'");
foreach (var row in rows)
   row.Delete();

above code work fine. how to convertthis code to LINQ?

上面的代码工作正常。如何将此代码转换LINQ

采纳答案by Sergey Berezovskiy

LINQ is not for deleting or modifying - it is for queryingdata. 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):

LINQ 不用于删除或修改 - 它用于查询数据。使用 LINQ,您可以选择应该删除的数据,然后手动删除这些数据(例如在 foreach 循环中或使用 ForEach 列表扩展名):

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:

更新:同样使用 LINQ to DataSet,您可以选择应保留在表中的所有行并从这些行创建新的 DataTable:

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

回答by Suraj Singh

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

回答by Damith

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

您使用 for 循环或 while 循环删除行而不是 foreach

below is non linq solution

下面是非 linq 解决方案

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

LINQ

LINQ

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

回答by Mohamed Salemyan

Try this inline lambda code with extension methodes:

试试这个带有扩展方法的内联 lambda 代码:

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

回答by Golda

Try this

尝试这个

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

回答by Lev Z

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

回答by Captain Fantastic

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?

我广泛搜索(嗯,超过四个谷歌搜索)来解决这个问题,最后我最终收集到(以上在 Sergey Berezovskiy 的帖子中)LINQ 不会删除 - 所以你使用 LINQ 来选择你想要的行想通过正在使用的数据库技术的“通常”机制摆脱和删除它们。似乎使所有关于 LINQ 的与数据库无关的宣传变得非常愚蠢?

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

这确实有效,尽管通过更多的实验,可以将两个“For Each”循环减少为一个。

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.

仅供参考,REPLY 对象有点像 Error 对象——我只是打包了错误消息、二进制通过/失败标志和其他一些东西,这样我就可以从查询中传回大量内容并(最终)向用户显示错误.

  ' <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