Solved

I need someone to explain parts of a LINQ query...

Posted on 2008-06-23
15
581 Views
Last Modified: 2013-11-26
I am not sure of the syntax of a LINQ query, please identify the following items:
1.  From f In Th.AsEnumerable()   ' can "f" be any name I set it to?
2.  In th.AsEnumerable() ' is "th" the datatable that I need to find the data using the subsequent 'Select" operator?
3.  f.Field(of string)("vocab")  ' in this code segment, is ' vocab ' one of the field in the ' th ' dataset datatable?
4.  dim thquery as object  ' can I declare thquery as an object inside the LINQ contex?
5.  For Each f in thquery  ' in the place of and the content of f need to be the same as the f in above item #1
6.  WHY is my LINQ query won't ge executed in my For Each f in thquery...Next loop?
Dim tiu As DataTable = ds.Tables(DtTableN)

        Dim db As New dbhDataSet()

        Dim Th As DataTable = db.Tables("th")

        dim thquery as object

        Dim row As DataRow

For Each row In tdt.Rows

thquery = From f In Th.AsEnumerable() Where f.Field(Of String)("vocab") = row(0).ToString() AndAlso Not f.Field(Of String)("vocab") = IsDBNull(row(0).ToString()) Select New With {.v = f.Field(Of String)("vocab")}

next

For Each f In thquery

            myrowTh = _vDtTh.NewRow()

            myrowTh(mycol) = f.v

            myrowTh(mycolgPt) = f.g

            myrowTh(mycolsubHead) = f.s

            myrowTh(mycolkey) = f.ke

            _vDtTh.Rows.Add(myrowTh)

        Next

Open in new window

0
Comment
Question by:isischen
  • 8
  • 7
15 Comments
 
LVL 21

Expert Comment

by:naspinski
ID: 21852349
1.  Yes, 'f' can be anything.  Sometimes it helps to be more descriptive with your name.  You will just have to keep it consistent within the query itself -- change 'f' and the beginning, change it throughout the query

2. 'Th.AsEnumerable()' is teh set of data you are searching through in the following statement

3. Yes

4. It is even easier, the new 3.5 architecture uses inference.  SO, youc an get rid of that whole line and instead just do this:
Dim thquery = From f In ...

5. 'f' in this case can be anything you want it to be, and does not relate tot eh 'f' above.  Each 'f' is in it's own statement and knows nothing of the other one.

6. Not totally sure I understand this question, but: The LINQ query calls it one time and makes a collection so you do not need to make multiple trips to the DB.

Please let me know if you need any more explanation on anything.
0
 

Author Comment

by:isischen
ID: 21852704
Thank you for answering question 1 thru 5. The last question is to seek an expert's eye to go through my code snippet to find bug because when I debug  the for each...next code block was skipped over---
         For Each f In thquery
            myrowTh = _vDtTh.NewRow()
            myrowTh(mycol) = f.v
            myrowTh(mycolgPt) = f.g
            myrowTh(mycolsubHead) = f.s
            myrowTh(mycolkey) = f.ke
            _vDtTh.Rows.Add(myrowTh)
        Next
so, no result derived from my LINQ query!
Just before I post this comment, I add 'system.data.linq' and 'Microsoft.visual basic.linq' to project reference but still not able to get any data out of the 'Th' dataset datatable!
Any idea of where else to look for bugs?
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21852850
You are correct it is not returning anything.
Have you verified that TH has data inside of it?  Try binding it to a gridview to make sure.
0
 

Author Comment

by:isischen
ID: 21853046
Yes, there is data inside the Th datatable when do a preview of dataset. However, there are more then 2 row of voc column match one row(0).tostring. And I have the following imports statements:
Imports System.Data
Imports System.Data.DataSet
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Access
Imports Microsoft.Office.Interop.Word
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Data.Common
Imports System.Collections.Generic
Imports System.Text
Imports System.Data.SqlClient
Also, I downloaded LINQ PREVIEW yesterday but have not read it in order to use it.

I can't bind result to gridview with this error message:
Unable to cast object of type 'System.Data.EnumerableRowCollection`1[VB$AnonymousType_1`4[System.String,System.String,System.String,System.String]]' to type 'System.Data.EnumerableRowCollection`1[System.String]'.

I have set the argument type in the receiving sub to be a System.Data.EnumerableRowCollection(Of String) and receive the above error message.
Thank you.
0
 

Author Comment

by:isischen
ID: 21853229
at this post in expert-exchange:
www.experts-exchange.com/Microsoft/Development/.NET/LINQ/Q_23335709.html - 77k -
it use a microsoft reporting service...I wonder if I need to use that or if I can just add
this:
//Get Connection String from App.Config
                string connStr = System.Configuration.ConfigurationManager.ConnectionStrings
                                           ["MyConnectionString"].ConnectionString;

                //Get Database Connection
                DALDataContext DataContext = new DALDataContext(connStr);
                               
                // create typed table
                Table<Appointment> appointments = DataContext.GetTable<Appointment>();

Is the latter of something necessary?
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21853232
you are not connecting to anything from what it looks like... why would you need that?
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21853240
looking at your query, it seems that you are looking for a single row, am I correct?

if that is teh case, your query would do a lot of unnecessary checking, try something like this (just for testing at least now)

thquery = (From f In Th.AsEnumerable() select f).First()

that will just pull the first row.

the foreach is really unnecessary, as you are only going o run it once.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:isischen
ID: 21859100
I tried to do this---dim boundtable as datatable=thquery.copytodatatable()
but my intellisense did not provide the copytodatatable option when I typed thquery. '?
Maybe I missed to add reference to or imports something I am not aware of!
I did not get a result from tyring something similar to what you suggested--
thquery = (From f In Th.AsEnumerable() Where f.Field(Of String)("voc") = "jones" Select New With {.v = f.Field(Of String)("voc").First()})
Debugging will skip over the code block of:
            For Each f In thquery
            Console.WriteLine("{0}", f.v.ToString)
            next
And, when I tried to do without the 'For each f in thquery', I did not know how else to replace 'console.writeline("{0}", f.v.tostring)
Thank you.
0
 

Author Comment

by:isischen
ID: 21859245
I received "System.Data.EnumerableRowCollection`1[VB$AnonymousType_0`1[System.Char]]"
as the output of ' console.writeline("{0}",thquery.Tostring) ' when I am expecting a "199" string datatype.

0
 
LVL 21

Accepted Solution

by:
naspinski earned 500 total points
ID: 21862859
Slow down here, I think you are trying to do too much at once.  

Let's make sure that a query in general is working here.  

First off, I don't think you are using Field() correctly at all.  Since f in this case is going to be a DataRow, you are going to have to search it like a DataRow.  Your query is a bit off.

You are running an equals vs a dbNull... are you trying to do that? You are testing if f.Field(Of String)("vocab") is true or false.  I am not sure what your table is, but that seems like it will not return anything.

Also, your select query does not include everything in f, so it seems to be off as well.

Try this for replacing line 7 and down.  If this works we can move on.

Try this
Dim thquery = From f In dt.AsEnumerable() Select f
 

For Each f In thquery

   Response.Write(f("vocab") & "<br />")

Next
 

'if you are going to check against  a column in the DataRow' 

'you have to access it like a DataRow'

'instead of f.Field(Of String)("vocab"), use:'

'f("vocab")'

Open in new window

0
 
LVL 21

Expert Comment

by:naspinski
ID: 21862863
should list out all the "vocab" values in the table
0
 

Author Comment

by:isischen
ID: 21863170
I read the LINQ PREVIEW and did f!vocab and ruin my project totally. I now have error in the visual studio generated class!
With vb.net 2008 express version, I can't see the datatable.LOADSEQUENCY(query) on my intellisense.
Thinking of download the VISAUL STUDIO 2008 professional (trial).  What do you think?
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21863191
Not completely following what happened, but VWD will do just fine.  Maybe uninstall and reinstall it?

VS is great, but it is expensive and large (it is what I use and recommend).  It is up to you.
0
 

Author Comment

by:isischen
ID: 21871279
Thank you for folllowing up with me. Anyway, I have tried to uninstall and reinstall Visual Basic.net 2008 express.  Having trouble with 'add datasource wizard' it keep giving me a 'can't establish relation' message at the end of click 'finish'. BUT, I can see my data using 'preview data'. So, I went ahead and revise my code to read as
 dim thquery= from f in In dt.AsEnumerable() Select f
and also tried this
 dim thquery= from f in In dt.AsEnumerable() where f("key")="away" Select new with {.s=f("subHead")}
all come the rest with the yellow hightlight on this
 for each f in thquery
with a invalidoperationexception error of 'sequence contain no element'
Oh, I found out that if I add reference to 'system.data.extension' it will cause the vb.net generated code to become full of errors.
Thank you.

 
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21871297
ok, that just means that your query is not returning any data, therefore it means that dt doesn't have any data inside of it.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now