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);
}
' <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
7条答案
按热度按时间kxe2p93d1#
LINQ不是删除或修改,而是查询数据。使用LINQ,您可以选择需要删除的数据,然后手动删除这些数据(例如:在foreach循环中或使用ForEach列表扩展):
UPDATE:同样使用LINQ to DataSet,您可以选择应该留在表中的所有行,并从这些行创建新的DataTable:
xe55xuns2#
尝试使用扩展方法的内联lambda代码:
swvgeqrz3#
使用for循环或while循环删除行,但不使用foreach
以下是非线性解决方案
LINQ
8ftvxx2r4#
6qfn3psc5#
试试这个
hiz5n14c6#
我搜索了很多地方(嗯,超过四次谷歌搜索)来寻找这个解决方案,最后我终于收集到(上面在Sergey别列佐夫斯基的帖子中)LINQ不做删除-所以你使用LINQ来选择你想要删除的行,并通过正在使用的数据库技术的“通常”机制删除它们。似乎使所有关于LINQ的数据库不可知的宣传变得很愚蠢?
这确实可行,尽管多做一些实验,人们可能能够将两个'For Each'循环减少到一个。
我有一个属性表,我想删除所有具有选定属性名(第三个关键字段)的条目,为特定的ObjectType(第一个关键字段),我想出了这个。
仅供参考,REPLY对象有点像Error对象-我只是打包了错误消息,一个二进制Pass/fail标志和一些其他东西,这样我就可以从查询中传回大量的内容,并(最终)将错误显示给用户。
f0brbegy7#