2015-09-11 38 views
0

我試圖使用linq查詢從vb中的數據庫中查詢值,但得到了一些錯誤。如何在vb.net中使用linq查詢數據表中的單個值

這裏是我的代碼:

For Each cl In clients 
Dim cn As DataTable 
    cn = getClients() #datatable with two columns, client code (cln_idck) and client name (cln_name) 
Dim clientname As String 
clientname = From cntable In cn Where cntable.Item("cln_idck") = cl Select (cntable.Item("cln_name")).ToString() 

#do something 
Next 

我只是試圖抓住客戶名稱,並使用客戶端代碼搜索放入字符串變量CLIENTNAME。上面的代碼給了我一個錯誤。

「範圍變量名無法比擬的成員的名字‘這是爲什麼不工作對象’類」

任何想法?

感謝您的幫助!

拉斐爾

更新:

客戶端(字符串)列表,具有客戶端代碼

Dim clients As New List(Of String) 
    clients.Add("Cln1") 
    clients.Add("Cln2") #etc. 
+0

什麼是_clients_? – Steve

+0

嗨,對不起,不說明。客戶端是一個包含客戶端代碼的列表(字符串)。 –

+0

可能重複的[爲什麼我不能在VB中項目ToString()?](http://stackoverflow.com/questions/4646724/why-cant-i-project-tostring-in-vb) – DavidG

回答

0

選擇返回一個IEnumerable(Of T)已(你與工作你的DataTable的DataRows讓你得到一個IEnumerable(Of DataRow)。

如果你想獲得字段cln_name中的字符串,你首先需要轉換你的結果[R查詢字符串枚舉,然後兌現元素

For Each cl In clients 
    Dim clientname = (From cntable In t Where cntable.Item("cln_name") = cl 
        Select (cntable.Item("cln_name").ToString())).First() 

    Console.WriteLine(clientName) 
Next 

這當然是基於CL的每一個元素在你的表精確匹配的假設。在這種情況下,您應該將First更改爲FirstOrDefault,並通知您的clientName字符串可能爲null(Nothing)

+0

工作!感謝@Steve的幫助。 –

相關問題