DataTable.Select.Where VB.Net - 删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13978687/
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-09-09 16:30:47  来源:igfitidea点击:

DataTable.Select.Where VB.Net - Delete rows

vb.netdatatablewheredelete-row

提问by XstreamINsanity

I'm currently pulling information using a query that I'm not allowed to tamper with:

我目前正在使用一个我不允许篡改的查询来提取信息:

Dim dt As DataTable = BLL.GetData(variable).Tables(0)

Immediately afterwards, I'm removing any records where a field begins with a specific value:

紧接着,我将删除字段以特定值开头的所有记录:

For Each dr As DataRow In dt.Rows
    If dr.Item(2).ToString().StartsWith("value") Then
        dr.Delete()
    End If
Next

What I'd really like to do is something like:

我真正想做的是:

dt.Select.Where(field1 => field1.StartsWith("value")).Delete()

I know that is not the syntax of it and I'm probably very off from what it would be like. The For Eachworks fine, I'm just trying to "simplify" it. Any idea? Any and all help is appreciated.

我知道这不是它的语法,我可能与它的样子很不一样。该For Each作品很好,我现在只是想“简化”了。任何的想法?任何和所有的帮助表示赞赏。

回答by Justin Niessner

Actually, your initial code is probably the cleanest and most straight forward.

实际上,您的初始代码可能是最干净、最直接的。

To delete items using LINQ, you first need to read them into a separate collection, then loop through that collection and call Delete on each record. If you'd rather go that route, you could try:

要使用 LINQ 删除项目,您首先需要将它们读入一个单独的集合,然后遍历该集合并在每条记录上调用 Delete。如果你更愿意走那条路,你可以尝试:

Dim records = dt.Rows.Where(Function(r) r.StartsWith("value")).ToList()
For Each r In records
    r.Delete()
Next

回答by Christopher K

The answer I think you are looking for is below from Microsoft. https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

我认为您正在寻找的答案来自 Microsoft。https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

Dim table As DataTable = DataSet1.Tables("Orders")

Dim table As DataTable = DataSet1.Tables("Orders")

' Presuming the DataTable has a column named Date.
Dim expression As String
expression = "Date > #1/1/00#"
Dim foundRows() As DataRow

' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)

Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
   Console.WriteLine(foundRows(i)(0))
Next i