Home > Fun, Software Development > Fun with Anonymous Types and LINQ

Fun with Anonymous Types and LINQ

Ben Yoder: LINQ

March 24th 2009 | Ben Yoder

Fun with Anonymous Types and LINQ

A new feature introduced in C# 3.0—anonymous types and their proper usage—has sparked some debate.  While some may feel that they distract from code clarity, they can be used for standard object initialization, such as:

—————–
var f = new FakeClass()
—————–

or primitive types

—————–
var i = 1;
—————–
In these cases, anonymous types add little to code readability.  In the case of initializing primitive data types, they really don’t save much typing or make a programmers life any easier.  Although anonymous types may not add much to standard object and type initialization, they are extremely handy for defining tuples and collections with LINQ.  For example, instead of having to define a struct or class of read-only properties, you could initialize the type like this:

—————–
var person = new {FirstName=”James”, LastName=”Ingram”};
var persons = new {first = new {FirstName = “James”, LastName = “Ingram”}
,second = new {FirstName=”Kenny”, LastName = “Loggins”}};
—————–

And even better, once a composite type is initialized, intellisense picks up on the properties making them easy to reference:

—————–
Console.WriteLine(person.FirstName);
—————–

We can also do fun things with delegates and functions with composite objects.  By specifying two different delegate functions and setting the “Join” property of the person object we can specify how each person should join their names.

—————–
Func<string, string, string> ReverseJoin =
(first, last) => last + “, ” + first;
Func<string, string, string> NormalJoin =
(first, last) => first + “, ” + last;

var persons = new {first = new {FirstName = “James”, LastName = “Ingram”, Join = ReverseJoin}
,second = new {FirstName=”Kenny”, LastName=”Loggins”, Join = NormalJoin}};
—————–

This behavior can be nicely leveraged in LINQ queries.  Since the compiler infers a type for the left hand side at build time (Check out the IL after compiling some code with anonymous types to see for yourself) there is no need for casting or conversions.  With anonymous types and LINQ we can write something like:

—————–
Func<string, string, string> ReverseJoin =
(first, last) => last + “, ” + first;
Func<string, string, string> NormalJoin =
(first, last) => first + “, ” + last;

var persons = new[]{
new {FirstName = “James”, LastName = “Ingram”, Join = ReverseJoin},
new {FirstName=”Kenny”, LastName=”Loggins”, Join = NormalJoin}
};

foreach (var person in from p in persons where p.LastName == “Ingram” select p)
{
Console.WriteLine(person.Join(person.FirstName, person.LastName));
}
Console.ReadLine();
—————–

Anonymous types aren’t really meant for replacing that standard class or initialization, its much more advantageous to use it with the set based operations of LINQ.  The example above may be somewhat contrived, but it’s handy that due to the inferred creation of the anonymously typed objects there was no need to create any classes.  Sure we could have created a Person class that specified properties for First and Last names, and methods to join them, and then looped through each item in the collection to check the LastName field.  That would have been a valid way of getting the same result, but with the combination of Anonymous types and LINQ we can write the same functionality in a more concise manner.


Ben Yoder is a Senior .NET developer at Thycotic Software Ltd. Thycotic is recognized for providing Agile TDD Training and Agile .NET Consulting Services, and its flagship password management software Secret Server.

  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: