Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this linq query?

Tags:

vb.net

linq

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim ds As DataSet
    ds = getData()
    Dim dt As DataTable = ds.Tables(0)
    Dim gridViewData = From r As DataRow In dt.Rows Select r.Item("foo"), r.Item("bar")
    GridView1.DataSource = gridViewData
    GridView1.DataBind()
End Sub

I just wrote the preceeding code and I get the following compile-time error: "Range variable name can be inferred only from a simple or qualified name with no arguments". Why do I get this error? How can I fix my code?

like image 320
Vivian River Avatar asked Aug 16 '10 14:08

Vivian River


2 Answers

EDIT: Okay, I understand the problem now. It's in the projection. Try this:

Dim gridViewData = From r As DataRow In dt.Rows _
                   Select Foo = r.Item("foo"), Bar = r.Item("bar")

Basically it didn't know what to call the properties in the projection.

like image 185
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet


Unfortunately, I don't know the VB syntax for this, so I'll just have to show the C# and hope you can work it out:

from DataRow r in dt.Rows
select new 
{
     r.Item("Foo"),
     r.Item("bar")
}

This is saying "Create a new class with two properties", but it has no idea what you want those properties named. If you had done something like this:

from DataRow r in dt.Rows
select new 
{
     r.Count,
     r.NumRows
}

Then it would assume that you wanted the properties called Count and NumRows, but with yours, all it has to go on is Item, which is used by both.

It fix this, you must specify names, explicitly:

from DataRow r in dt.Rows
select new 
{
     Foo = r.Item("Foo"),
     Bar = r.Item("bar")
}
like image 33
James Curran Avatar answered Sep 28 '22 00:09

James Curran