Learning Curve…

Archive for the ‘C#’ Category

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

Author

Learning days (Calendar)

October 2017
M T W T F S S
« Jun    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Knowledge Bank (Archives)

I am on Twitter

Blog Stats

  • 510,411 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: