VB.Net Linq数据表存在

时间:2010-05-05 13:14:50

标签: vb.net linq datatable

我想使用Linq而不是以下函数:

Friend Function IsCollectionInTable2(ByVal apps As DataTable, ByVal collectionId As String) As Boolean
    For Each row As DataRow In apps.Rows
        If row("CollectionId").ToString = collectionId Then Return True
    Next
    Return False
End Function

我能做的最好的事情如下:

Friend Function IsCollectionInTable(ByVal apps As DataTable, ByVal collectionId As String) As Boolean
    Return (From row In apps.AsEnumerable()
             Where (row.Field(Of String)("CollectionId") = collectionId)
             Select row.Field(Of String)("CollectionId")).Count > 0
End Function

我想在上面的功能中使用Exists或Any。性能可能是一个问题,

2 个答案:

答案 0 :(得分:1)

我找到了一个似乎有效的解决方案:

Return (From row In apps.AsEnumerable()
        Where row.Field(Of String)("CollectionId") = collectionId).Any()

我希望这和以下一样快:

For Each row As DataRow In apps.Rows
If row("CollectionId").ToString = collectionId Then Return True
Next
Return False

答案 1 :(得分:0)

DataTable.Select Method (String)怎么样(对不起我的VB很差)

    Dim expression As String
    expression = string.Format("CollectionId = '{0}'", collectionId)
    ' Use the Select method to find all rows matching the filter.
    return apps.Select(expression).Count > 0