New Array of Anonymous Objects

While coding up a couple of prototype LINQ queries this morning I came across a rather interesting syntax using anonymous types and object initializers.  I wanted to show an example of using a where clause upon a property of an object but didn’t want to put a bunch of plumbing around it just to set up the example.  In my head an array containing three Person objects would suffice, with each person object having Name and Age properties that I could use in my query.  I wasn’t sure if this would compile but dropped it into the wonderful LinqPad and sure enough found that it compiled right away, giving me exactly the results I was looking for.

from person in new [] {
new { Name=“Bob”, Age=28 },
new { Name=“Ted”, Age=22 }
new { Name=“Sally”, Age=25 } }
where person.Age < 26
select person

I can declare a new [] { <set of anonymous types> } right there in the query, saving me the job of creating all of the plumbing around it just for the sake of the sample.  Cool!

This entry was posted in Technology, Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *