SQL LINQ查询:选择特定列
今天,我需要在VB.net中将LINQ查询写入数据库表,但我对SQL/LINQ是新手。下面的函数用于用数据库表中与QuestionType匹配的所有可能的“问题”填充字符串列表 但是,只要有匹配项,我只想选择一列,即QuestionText列,而不是所有数据SQL LINQ查询:选择特定列,sql,vb.net,linq,Sql,Vb.net,Linq,今天,我需要在VB.net中将LINQ查询写入数据库表,但我对SQL/LINQ是新手。下面的函数用于用数据库表中与QuestionType匹配的所有可能的“问题”填充字符串列表 但是,只要有匹配项,我只想选择一列,即QuestionText列,而不是所有数据 Public Shared Function RetrieveQuestions(ByVal QuestionType) As List(Of String) Dim db As New DBDataContext() db
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不是System.Collections.Generic.List(字符串)的成员”。QuestionText在我的SQL数据库中定义为varchar,所以我知道它肯定是一个字符串。我不是想把QuestionText设置为字符串列表,而是想把它添加到字符串列表的末尾。直接回答:你需要把整个
放在一个循环中,如果(问题不是空的),那么
块就像一个循环一样。正如编译器正确告知的那样,i
变量保存整个列表,而不是其中的一项。也许你忘了你留下了LINQ查询
一个更好的解决方案:我相信你可以只使用和q.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) = (
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