Learning Curve…

Anonymous type…

Posted on: January 3, 2012

An anonymous type is a type whose name you don’t define up front like you do with other types such as classes. Instead, you construct the anonymous type by selecting data and then let the compiler infer the type for you.

Creating an anonymous type is easy; instead of selecting the actual object using something like Select TableName, you use the new keyword in C# and New With in Visual Basic and then define the properties you want to select between a pair of curly braces:

For example:-

var varName= from r in tableName

select new { r.Id, r.Title};

Although the type is anonymous and cannot be accessed by name directly, the compiler is still able to infer the type, giving you full IntelliSense for the new properties that were selected in the query.

Besides directly selecting existing properties — as shown in the query that selected the Id, and Title, you can also make up property values and give them different names as you go.

For example, the following query creates a new anonymous type that renames the Id as

Number, limits the Title to the first 20 characters, and contains a Boolean value that determines whether the item has been updated in the database previously:

var varName = from r in tableName

Select new

{

Number = r.Id,

Title = r.Title.Substring(0, 20),

HasBeenUpdated = (r.UpdateDateTime >

r.CreateDateTime)

};

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Author

Learning days (Calendar)

January 2012
M T W T F S S
« Dec   Feb »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Knowledge Bank (Archives)

I am on Twitter

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Blog Stats

  • 510,129 hits

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 43 other followers

%d bloggers like this: