views:

113

answers:

1

I am using the Dynamic Linq Library that Scott Guthrie describes here.

Scott Guthrie's examples are great and I have used the dynamic Where statements quite a bit.

Now, however, I am faced with a situation where I need to use the dynamic select functionality. Scott Guthrie shows a screenshot of this functionality (in the very last screenshot in the article) but very cleverly never explains it.

The problem is, even though the code compiles and runs, I don't see how it can possibly work in any useful manner. Perhaps with reflection?

Here is an example (remember, you must use the Dynamic Linq Library that Guthrie describes in the article above, this is not the normal Linq System.Linq).

In my sample here, I have a Users table with a UserId, FirstName, and LastName fields. But it really doesn't matter what database you use. The issue is very simple to reproduce. Here is my sample code:

First make sure you have this using statement on top:

    using System.Linq.Dynamic;

Then you can run the following code:

using (DataClasses1DataContext dcdc = new DataClasses1DataContext())
        {
            var x = dcdc.Users.Select("new(UserId, FirstName, LastName)");
            foreach (var item in x)
            {                    

                Console.WriteLine(item.ToString());
            }
        }

As you can see, this compiles and runs just fine. You get all your records back from the database. However, there is no way I can find to actually access the members of the new anonymous type.

Because the Select query is a string, there is no type inference at design time. So I cannot write:

Console.WriteLine(item.UserId);

The compiler has no idea that the anonymous type item has a member named UserId. So that code will not even compile (even though if you pause the debugger during the For..Each loop you will see that the debug window sees that there are UserId, FirstName and LastName members.

So... how is this supposed to work? How do you gain access to the members of the anonymous type?

+1  A: 

It will work fine for data-binding (I suspect this is its intended use-case), which uses reflection under the hood. It will also work fine with dynamic in .NET 4.0:

foreach (dynamic item in x) { 
    Console.WriteLine(item.UserId);
}

Other than that... reflection or TypeDescriptor.

foreach (object item in x) {
    Console.WriteLine(item.GetType().GetProperty("UserId").GetValue(item, null));
}
Marc Gravell
As I suspected... but thanks for the confirmation.
Clever Human