2017-04-10 35 views
0

我有如下功能。我想使它更通用。希望能够发送数据列的参数和每个列的期望值。方法的如果条件基于列表属性

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个预期值。在这种情况下,它看起来应该如下:

的伪代码:

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

所以词典(只是举例)将包含列名称和预期值的每一个。 在我们的例子中,当我送他们三个应该构建方法,例如这样:

如:

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 
+0

这里有个问题吗? – user2366842

+0

@ user2366842问题是如何做到这一点 – Dino

+0

条件调节是不可能的。您不能在您的If条件中动态追加“AND”。 – CurseStacker

回答

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