方法&n;如果条件基于列表属性

时间:2017-04-10 21:49:29

标签: vb.net

我的功能如下。我想让它更通用一点。希望能够为每个参数发送数据表列的参数和期望值。

Private Function SearchDtValue(dt As DataTable, Value1 As String, Value2 As String) As String
   For Each row As DataRow In dt.Rows
       If row("Name") = Value1 And row("Age") = Value2 Then
          Return row("Surname")
       End If
   Next
   Return Nothing
End Function

在我的新函数中,可以获得不同数量的列及其值进行检查,例如我想检查3列数据表,并说明每个要比较的3个预期值。在这种情况下,它应该看起来如下:

Psuedo代码:

SearchDtValue(dt as DataTable, dictionary(Of String, String),colNameValueToBeRetreived)

所以字典(例如)将包含每个列的名称和期望值。 在我的示例中,当我发送其中三个时,它应该以这种方式构造方法:

e.g:

    Dictionary could contain:
    Age, 30
    Name, John
    Surname, Brzenk

colNameValueToBeRetreived= Address

根据paraemters,方法看起来像这样:

  For Each row As DataRow In dt.Rows
       If row(Age) = "30" And row(Name) = "John" And row(Surname) = "Brzenk" Then
          Return row(colNameValueToBeRetreived)
       End If
   Next

1 个答案:

答案 0 :(得分:0)

尝试以下代码。假设字典具有键作为列名称和值作为键的预期列值。

Private Function SearchDtValue(dt As DataTable, cols As Dictionary(Of String, String), colNameValueToBeRetreived As String) As String
    Dim returnValue As String = Nothing

    Try
        Dim matchCount As Integer = 0
        For Each row As DataRow In dt.Rows
            For Each col In cols
                If row(col.Key).ToString = col.Value Then
                    matchCount = matchCount + 1
                End If
            Next

            If matchCount = cols.Count Then
                returnValue = row(colNameValueToBeRetreived).ToString
                Exit For
            End If
        Next
    Catch ex As Exception
        Throw New Exception("Error in matching column values")
    End Try

    Return returnValue

End Function