Alex Rivera | Logout

How can I get a value of a property from an anonymous type?

Asked 2009-05-17T14:35:33.110
31

I have a datagrid populated by a Linq query. When the focused row in the datagrid changes I need to set a variable equal to one of the properties in that object.

I tried...

var selectedObject = view.GetRow(rowHandle);
_selectedId = selectedObject.Id;

... but the compiler doesn't care for this at all ("Embedded statement cannot be a declaration or labled statement").

It seems like the property should be easy to access. Inspecting the object during runtime shows all the properties I expect, I just don't know how to access them.

How can I get access to the anonymous object's property?

Edit for Clarifications:

I happen to be using DevExpress XtraGrid control. I loaded this control with a Linq query which was composed of several different objects, therefore making the data not really conforming with any one class I already have (ie, I cannot cast this to anything).

I'm using .NET 3.5.

When I view the results of the view.GetRow(rowHandle) method I get an anonymous type that looks like this:

{ ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }

My objective is to get the ClientId from this anonymous type so I can do other things (such as a load a form with that client record in it).

I tried a couple of the suggestions in the early answers but was unable to get to a point where I could get this ClientId.

Edit
Report

2 Answers

1

As JaredPar guessed correctly, the return type of GetRow() is object. When working with the DevExpress grid, you could extract the desired value like this:

int clientId = (int)gridView.GetRowCellValue(rowHandle, "ClientId");

This approach has similar downsides like the "hacky anonymous type casts" described before: You need a magic string for identifying the column plus a type cast from object to int.

answered 2009-05-17T16:49:25.097
0

If you know what you are doing and are not afraid of getting runtime errors when your code changes, you could cast your row data as dynamic:

var data = view.GetRow(rowHandle) as dynamic;  

int clientId      = data.ClientID;
string clientName = data.ClientName;
int jobs          = data.Jobs

No Compile-time verification. But it should work nicely.

answered 2013-07-23T08:36:34.753

Your Answer