grouping in linq using groupby operator

As in sql, objects can be grouped using the 'group by' operator in Linq. The below example demonstrates how to use 'group by' operator to group data in a dictionary. Using the below code we can group the products by their categories. The Dictionary() contains products and categories. Let us now we will see how to write a LINQ query to return groups of products.

The query shown below returns one group for each unique category from the dictionary. We can also give name to a group using into keyword. In the below query we have given a name to the group � productGroup.

The productGroup refers to new groups. In the query, the select keyword is used to return the result of the query. In the query, we write select productGroup; to return groups.

If you look at the �group by� clause, you will notice that the product.Value refers to the category in the dictionary.

Dictionary products;
products = new Dictionary();
products.Add("Product1", "Vegetables");
products.Add("Product2", "Vegetables");
products.Add("Product3", "Non Sodium Items");
products.Add("Product4", "Non Sodium Items");
products.Add("Product5", "Bakery Products");

Note that the below query returns groups of products ( not individual products) based on category.

var productGroups =
		from product in products
		group product by product.Value
		into productGroup
	    select productGroup;
foreach (var group in productGroups)
{
	Console.WriteLine("I found {0} {1}",group.Count(),group.Key);
	foreach (var product in group)
    {
       Console.WriteLine(product.ToString() + " ");
    }
}

To retrieve these groups, we have enumerated through the groups using for each loop as shown above. The output of the above query is given in fig.

The below given query is the extension of the above query and is used to display the groups in an ascending order.
var productGroups =
					from product in products
					group product by product.Value
					into productGroup
					orderby productGroup.Key
					select productGroup;
Observe the difference in the outputs.