2014-05-13 96 views
0

今天,我需要在VB.net中將LINQ查詢寫入數據庫表,但對於SQL/LINQ來說是新手。下面的這個函數是用來填充數據庫表中與QuestionType匹配的所有可能的「問題」的字符串列表。SQL LINQ查詢:選擇特定列

但是,我只想選擇一個單列,QuestionText列,而不是所有的數據,只要我有一個匹配。

Public Shared Function RetrieveQuestions(ByVal QuestionType) As List(Of String) 
    Dim db As New DBDataContext() 
    db.CommandTimeout = 300 
    Dim ListOfQuestions As List(Of String) = New List(Of String) 
    While True 
     Dim questionList As List(Of Question) = db.Questions.ToList 
     Dim question As List(Of String) = (From q As Question In questionList Where q.FormType = QuestionType Select q.QuestionText).ToList 
     Dim i As List(Of String) = question 
     If (question IsNot Nothing) Then 
      ListOfQuestions(ListOfQuestions.Count) = i.QuestionText //ERROR 
     Else 
      Exit While 
     End If 
    End While 
    Return ListOfQuestions 
End Function 

在上面的函數中,當我試圖用新的QuestionText更新我的列表時遇到錯誤。 「QuestionText不是System.Collections.Generic.List(Of String)」的成員「。 QuestionText在我的SQL數據庫中被定義爲一個varchar,所以我知道它絕對是一個字符串。我不是試圖將QuestionText設置爲字符串列表,而是將其添加到字符串列表的末尾。

回答

1

直接回答:您需要將整個If (question IsNot Nothing) Then塊放入類似For Each的循環中。當編譯器正確通知 - i變量包含整個列表,而不是其中的一個項目。也許你忘了你離開了LINQ查詢?

更好的解決方案:我相信你可以使用AndAlso q.QuestionText IsNot Nothing - 它不需要分配一個新列表並逐個填充它 - 下面的代碼應該可以做到這一點。

Public Shared Function RetrieveQuestions(ByVal QuestionType) As List(Of String) 
    Dim db As New DBDataContext() 
    db.CommandTimeout = 300 

    Dim ListOfQuestions As List(Of String) = (
      From q As Question In db.Questions.ToList 
      Where 
        q.FormType = QuestionType 
        AndAlso q.QuestionText IsNot Nothing 

      Select q.QuestionText 
    ).ToList 

    Return ListOfQuestions 
End Function