Grouping Operators

The grouping concept is something that you of course already know if you ever worked with data. Given a products collection, it would be useful dividing products into categories to provide a better organization of information. For example, consider the following Category class:

image

Now consider the following review of the Product class, with a new CategoryID property:

image

At this point we can write code that creates instances of both classes and populates appropriate collections, as in the following snippet:

image

image

To make things easier to understand, only two categories have been created. Notice also how each product now belongs to a specific category. To group foods into the Food category and beverages into the Beverages category, you use the Group By operator. This is the closing code of the preceding method, which is explained just after you write it:

image

The code produces the following result:

image

Basically Group By requires you to specify a key for grouping. This key is a property of the type composing the collection you are querying. The result of the grouping is sent to a new IEnumerable(Of T) sequence represented by the Into Group statement. Finally you invoke Select to pick up the key and items grouped according to the key; the projection generates an IEnumerable(Of anonymous type). Notice how you need a nested For..Each loop; this is because each item in the query result is composed of two objects: the key and a sequence of object (in this case sequence of Product) grouped based on the key. The same result can be accomplished using extension methods’ counterpart that work like this:

image

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.31.26