DataTable中的SQL IN运算符在VB.NET中选择方法

时间:2012-02-19 17:08:12

标签: vb.net

是否有一个函数可以在VB.net中的DataTable Select方法中编写它?

我想使用的SQL查询

SELECT id from mytable where id in ('a','b','c')

我有这个代码来创建查询,但如果我可以使用IN子句

那就太好了
    For Each typeitem In shapecb.Items
        If Stntypeitem.Selected = True Then
            If o = True Then
                sqlfil += " AND Shape = '" + typeitem.Value + "'"
            Else
                sqlfil += "Shape = '" + typeitem.Value + "'"
                o = True
            End If
        End If
    Next
    Dim bindtable As DataTable = dt.Clone
    Dim rows As DataRow() = dt.[Select](sqlfil)
    For Each row As DataRow In rows
        bindtable.ImportRow(row)
    Next

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

我不确定shapecb是什么类型,因此您可能需要更改我在演员表中指定的类型。 (我以为它是System.Web.UI.WebControls.DropDownList。)

Dim strings = _
    From item In shapecb.Items.Cast(Of ListItem)() _
    Where item.Selected _
    Select "'" & item.Value & "'"

Dim inList As String = String.Join(",", strings.ToArray())
Dim sql As String = "SELECT id FROM mytable WHERE id IN (" & inList & ")"

编辑(回应评论):

LINQ提供了一种替代的,通常更简洁的方法。同样的问题将以传统的方式解决:

Dim strings = New List(Of String)

For i As Integer = 0 To shapecb.Items.Count - 1
    Dim item As ListItem = shapecb.Items(0)
    If item.Selected Then
        strings.Add("'" & item.Value & "'")
    End If
Next

Dim inList As String = String.Join(",", strings.ToArray())
Dim sql As String = "SELECT id FROM mytable WHERE id IN (" & inList & ")"

传统方式通常比LINQ更快;但是,如果您有非常大的枚举(> 100000)或者进行非常精确的测量,则只会注意到差异。选择您觉得更容易使用的方法。

答案 1 :(得分:0)

您可以使用LINQ-to-DataSet过滤DataTable

Dim shapes = {"a", "b", "c"}
Dim tbl = (From row In dt.AsEnumerable
          Where shapes.Contains(row.Field(Of String)("Shape"))).CopyToDataTable

或流利的语法:

tbl = dt.AsEnumerable.Where(Function(r) shapes.Contains(r.Field(Of String)("Shape"))).CopyToDataTable