thebeebs | Anonymous Types
thebeebs
Learn the art of website security
 
 

Anonymous Types

by thebeebs 10. February 2009 07:01

Peter was asking on one of the forums, how to get information back from Linq when the information you required didn't really fit neatly into the object structure described by the Entity framework.

I thought I'd share with you something I've recently discovered, Anonymous Types, and how they can be used to solve this problem.

Lets pretend you have 2 tables product, and product description. Say for example you wanted the product Id and the product description but didn't require all the other product information.

In Linq you can do this by using anonymous types.

First lets use Linq to select our product class:

 

AnonType1

Next we need to join the the product description table.

 

AnonType2

Outside of a Linq query the syntax to create an anonymous type is as follows:

 

 AnonType3

 

Anonymous Types at first may look wrong or inefficient. Trust me though, despite how flaky these types may look they are properly complied classes in machine code they are not dynamic and do not have a performance hit in comparison to a struct or class. The only negative is that they feel wrong and you could argue they make code less readable.

 

Ok back to Linq, to use anonymous types in Linq you declare the new type in the select of the query:

 

AnonType4

 

The variable result will then be a list of these anonymous types. If you only want the first result you could do the following:

 

AnonType5

The variable result will now be an instance of the anonymous type and can be interrogated by it's properties:

 

anonTypes7

 

Just one important note. You should never pass an anonymous object out of a function or method boundary. Unless of course your objective is to generate really rubbishy code.

Tags:

Comments (2) -

Ge gwf
Ge gwf United Kingdom
5/3/2009 9:11:42 PM #

thanks a lot.I will try it out.

stratford upon avon hotels
stratford upon avon hotels United States
8/13/2011 10:36:19 PM #

Hey this is a great post. Could you keep me updated with any other info similar to this? If travelling to the UK why not stay at Stratford hotel and watch a Shakespear play

Comments are closed