2

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 Each works fine, I'm just trying to "simplify" it. Any idea? Any and all help is appreciated.

2 Answers 2

3

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:

Dim records = dt.Rows.Where(Function(r) r.StartsWith("value")).ToList()
For Each r In records
    r.Delete()
Next
Sign up to request clarification or add additional context in comments.

2 Comments

@user574632 - If you simply wanted a collection with the rows that don't start with "value", then yes. But the OP specifically says they want to delete the rows.
Hmmm, both ways might work. This is pre-draw to the screen, so either doing the NOT or deleting them might work.
0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.