2017-04-10 33 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