0

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.
6
  • Hi, sorry about not clarifying that. Client is a list(of string) that contains the client codes. Commented Sep 11, 2015 at 16:04
  • possible duplicate of Why can't I project ToString() in VB? Commented Sep 11, 2015 at 16:05
  • So it's the ToString on the end that is causing the problem. Wrap it in parentheses and it should work: Select ((cntable.Item("cln_name")).ToString()) Commented Sep 11, 2015 at 16:06
  • @DavidG, I saw that post and tried your above code but it still gives me an error, this time it says: 'system.data.enumerablerowcollection(of string) cannot be converted to string' Commented Sep 11, 2015 at 16:08
  • @RafaelVelásquez So the question I linked does answer your question but now you have another problem which Steve has sorted for you. Commented Sep 11, 2015 at 16:28

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.