Home » ASP.NET | Code | Headline

Anonymous Types

10. February 2009 by thebeebs 1 Comments

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.

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading