Rafael Velásquez
Rafael Velásquez

Reputation: 337

How to query a single value from a datatable using linq in vb.net

I'm trying to query a value from a datable in vb using a linq query but am getting several errors.

here's my code:

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

I'm just trying to grab the client name and put it into the string variable clientname using the client code to search. The above code gives me an error.

"range variable name cannot match the name of a member of the "object" class"

Any ideas why this isn't working?

Thanks for the help!

Rafael

update:

client is a list(of string) that has the client codes

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

Upvotes: 0

Views: 5108

Answers (1)

Steve
Steve

Reputation: 216291

Select returns an IEnumerable(Of T) (and you are working with the DataRows of your DataTable so you get an IEnumerable(Of DataRow).

If you want to get the string inside the field cln_name, you need first to transform the result of your query to an enumeration of strings, then materialize the element

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

This of course is based on the assumption that every element of cl has a precise match in your table. In that case you should change First to FirstOrDefault and be informed that your clientName string could be null (Nothing)

Upvotes: 2

Related Questions