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

时间:2013-09-17 15:52:17

标签: c# asp.net linq

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

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

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

7 个答案:

答案 0 :(得分:27)

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

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

foreach(var row in query.ToList())
   row.Delete();

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

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

答案 1 :(得分:8)

尝试使用扩展名为methodes的内联lambda代码:

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

答案 2 :(得分:1)

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

下面是非linq解决方案

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

LINQ

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

试试这个

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

答案 5 :(得分:0)

我搜索了很多(好的,超过四次谷歌搜索)以获得解决方案,最后我最终收集到了(在谢尔盖别列佐夫斯基的帖子上面)LINQ没有做删除 - 因此,您使用LINQ选择要删除的行,并通过常规&#39;删除它们。数据库技术的使用机制。似乎对LINQ的所有与数据库无关的宣传都很愚蠢吗?

这确实有效,尽管可以通过更多的实验来减少两个“每个人”。循环到一个。

我有一个属性表,我想删除所有具有特定ObjectType(第一个Keyfield)的属性名称(第三个键字段)的条目,我想出了这个。

FYI 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

答案 6 :(得分:-1)

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