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 ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.