Welcome to MSDN Blogs Sign in | Join | Help
Projection

[Table of Contents]  [Next Topic]

Projection is the abstraction of taking one shape of data and creating a different shape of it.  For instance, you could take a collection of one type, filter it and/or sort it, and then project a collection of a new type.

The Select extension method is what you use to implement projection on a collection.  You can pass a lambda expression to the Select extension method that takes one object from the source collection, and projects one object into the new projection.

Let's say that we have a collection of integers, and we want a new collection of strings of x's, where the string lengths are determined by the source collection of integers.  The following code shows how to do this:

int[] lengths =

    new[] { 1, 3, 5, 7, 9, 7, 5, 3, 1 };

IEnumerable<string> strings =

    lengths.Select(i => "".PadRight(i, 'x'));

foreach (var s in strings)

    Console.WriteLine(s);

 

This code produces the following output:

x

xxx

xxxxx

xxxxxxx

xxxxxxxxx

xxxxxxx

xxxxx

xxx

x

 

Or we could take an array of doubles, and project a collection of integers, casting each double to int:

double[] dbls =

    new[] { 1.5, 3.2, 5.2, 7.3, 9.7, 7.5, 5.0, 3.2, 1.9 };

IEnumerable<int> ints =

    dbls.Select(d => (int)d);

foreach (var i in ints)

    Console.WriteLine(i);

 

Or we can take a collection of elements from an XML tree, and project a collection of strings.  The strings projection contains the value of each element:

XElement xmlDoc = XElement.Parse(

    @"<Root>

        <Child>abc</Child>

        <Child>def</Child>

        <Child>ghi</Child>

      </Root>");

IEnumerable<string> values =

    xmlDoc.Elements().Select(e => (string)e);

foreach (string s in values)

    Console.WriteLine(s);

 

But in the real world, our projections will typically be much more involved than this.  For instance, we will often take a collection of some class, and project a collection of a different class.  Or we may project a collection of anonymous types (introduced in the next topic).

[Table of Contents]  [Next Topic]

 

Posted: Tuesday, April 22, 2008 11:21 PM by EricWhite

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker