Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
[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.
This blog is inactive.
New blog: EricWhite.com/blog
Blog TOCThe 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:
Dim lengths() As Integer = { 1, 3, 5, 7, 9, 7, 5, 3, 1 }
Dim stringCollection As IEnumerable(Of String) = _
lengths.Select(Function (i) "".PadRight(i, "x"C))
For Each s In stringCollection
Console.WriteLine(s)
Next
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:
Dim dbls() As Double = { 1.5, 3.2, 5.2, 7.3, 9.7, 7.5, 5.0, 3.2, 1.9 }
Dim ints As IEnumerable(Of Integer) = _
dbls.Select(Function(d) CInt(d))
For Each i In ints
Console.WriteLine(i)
Next
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:
Dim xmlDoc = _
<Root>
<Child>abc</Child>
<Child>def</Child>
<Child>ghi</Child>
</Root>
Dim values As IEnumerable(Of String) = _
xmlDoc.Elements().Select(Function(e) CStr(e))
For Each s In values
Console.WriteLine(s)
Next
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).