tags:

views:

654

answers:

4

Hi all,

Essentially i want to have a generic function which accepts a LINQ annonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.

hopefully the example below helps

say i have a person object with id, fname, lname and dob. i have a generic class with contains a list of objects.

i return an array of persons back

my code snippet wule be something like

dim v = from p in persons.. select p.fname,p.lname

i now have an annonymous type from system.collections.generic.ineumerable(of t)

to bind this to a grid i would have to iterate and add to an array e.g.

dim ar() as array

for each x in v ar.add(x) next

grid.datasource = ar

i dont want to do the iteration continually as i might have different objects

i would like a function which does something like below:

function getArrayList(of T)(dim x as T) as array()

dim ar() as array

for each x in t ar.add(x) next

return ar

end

hope that clairifies. how can i get a generic function with accepts an annonymous list of ienumearable and returns an array back. unfortunately, the one i have does not work.

many thanks in advance as any and all pointers/help will be VASTLY appreciated.

regards

azad

+1  A: 

Your question is a little unclear, so I'm not sure how much my answers will help, but here goes...

Richard Ev
A: 

I'm not sure that you can easily pass anonymous objects as parameters, anymore than you can have them as return values.

I say easily, because:

[Try the code formatting option on your question (the " button in the editor), it would make it easier to read the parts of your question which are code snippets.]

Benjol
+2  A: 

You'd just call ToArray. Sure, the type is anonymous... but because of type inference, you don't have to say the type's name.

From the example code:

    packages _
    .Select(Function(pkg) pkg.Company) _
    .ToArray()

Company happens to be string, but there's no reason it couldn't be anything else.

David B
+3  A: 

You can bind a grid directly to the array of anonymous types. Here's an example:

        var qry = from a in Enumerable.Range(0, 100)
                  select new { SomeField1 = a, SomeField2 = a * 2, SomeField3 = a * 3 };
        object[] objs = qry.ToArray();
        dataGridView1.DataSource = objs;

Note also the call to ToArray, which eliminates the need for a loop. I also assign it to a type of object[] to demonstrate that you could pass that around as its type if you want.

TheSoftwareJedi