O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Projection Strategies

Object Initializers

So far, all our select clauses have projected scalar element types. With C# object initializers, you can project into more complex types. For example, suppose, as a first step in a query, we want to strip vowels from a list of names while still retaining the original versions alongside for the benefit of subsequent queries. We can write the following class to assist:

	class Temp ProjectionItem
	{
	  public string Original;    // Original name
	  public string Vowelless;   // Vowel-stripped name
	}

and then project into it with object initializers:

	string[] names = { "Tom","Dick","Harry","Mary","Jay" };

	IEnumerable<TempProjectionItem> temp =
	  from n in names
	  select new TempProjectionItem
	  {
	    Original  = n,
	    Vowelless = Regex.Replace (n, "[aeiou]", "")
	};

The result is of type IEnumerable<TempProjectionItem >, which we can subsequently query:

	IEnumerable<string> query =
	  from   item in temp
	  where  item.Vowelless.Length > 2
	  select item.Original;

	// RESULT: Dick, Harry, Mary

Anonymous Types

Anonymous types allow you to structure your intermediate results without writing special classes. We can eliminate the TempProjectionItem class in our previous example with anonymous types:

var intermediate = from n in names 
	  select new
	  {
	    Original = n,
	    Vowelless = Regex.Replace (n,"[aeiou]", "")
	  };

	IEnumerable<string> query =
	  from item in intermediate
	  where item.Vowelless.Length > 2
	  select item.Original;

This gives the same result as the previous example, but without needing to write ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required