>Query keywords – group and into

>

group (… by ): Is used for grouping the results based on a key. The key can be a plain or composite key. In Linq, the result of grouping is a List of Lists. You can think of it as data grouping in a report rather than a flat rows*columns representation of a table. The result is  ( A Key per group, Matching Items per key ) collection – officially IGrouping ( TKey, TElement ). Another feature of group is that it is a keyword that can be used to end a query ( a query should end either with a select or group ).

A simple grouping would be to group Northwind Customers by their country values:

from c in Customers group c by c.Country

You can "group", "select" or "join" into an intermediary result using the keyword "into" and continue the query on that ‘sub query’. It is like doing a sub query in SQL. "Key" is a property that is generated automatically and holds the group’s key. i.e.:

from c in Customers
                group c by c.Country into countries
                select new
                {
                    Country = countries.Key,
                    Customers = from cus in countries 
                               
orderby cus.City, cus.CustomerID
                                select new { cus.CustomerID, cus.City }
                }

Here what we do is first we group the Customers by their country and ‘alias’ that ‘sub query’ as "countries". From that point on identifier "c" is not available to us (it is similar to SQL in that matter too). We continue with "countries" which is now a ( Country as key, Matching Rows ) collection.  

You can also group a group but IMHO it is a hard to understand syntax:

from c in Customers.Select( c => new {c.CustomerID, c.Region, c.City, c.Country} )
   group c by c.Country[0] into g1
   from cc in ( from c in g1 group c by c.Country )
   group cc by g1.Key

About cetinbasoz

A developer working primarily with C#,F#,VFP,SQL server, Silverlight,Linq ...
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s