Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using Anonymous Types with LINQ Queries

The most significant attribute of anonymous types in conjunction with LINQ is that they support hierarchical data shaping without writing all of the plumbing code or resorting to SQL. Data shaping is roughly transforming data from one composition to another. LINQ lets you do this with natural queries, and anonymous types give you a place to store the results of these queries.

This whole book is about LINQ, so Listing 1.14 shows a couple of LINQ examples without getting too far ahead in upcoming chapter material. Again, each example also has a brief description.

Listing 1.14. A Couple of Simple LINQ Queries to Play With Demonstrating Future Topics Such as Sorting and Projections

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace AnonymousTypeWithQuery
{
  class Program
  {
    static void Main(string[] args)
    {
      var numbers = new int[] {1, 2, 3, 4, 5, 6, 7};
      var all = from n in numbers orderby n descending select n;

      foreach(var n in all)
        Console.WriteLine(n);

      var songs = new string[]{"Let it be", "I shall be released"};
      var newType = from song in songs select new {Title=song};

      foreach(var s in newType)
        Console.WriteLine(s.Title);

      Console.ReadLine();
    }
  }
}

The first query—from n in numbers orderby n descending select n—sorts the integers 1 to 7 in reverse order and stuffs the results in the anonymous type all. The second query—from song in songs select new {Title=song}—shapes the array of strings in songs to an enumerable collection of anonymous objects with a property Title. (The second example takes an array of strings and shapes it into an array of objects with a well-named property.)

  • + Share This
  • 🔖 Save To Your Account