Grouping Operators

Grouping operations place data in groups based on a common attribute.

The query operator methods used to perform grouping operations follow: GroupBy and ToLookup.

The GroupBy method groups elements of a sequence based on a key selector function. Its syntax follows:

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
	this IEnumerable<TSource> source,
	Func<TSource, TKey> keySelector
)

Review an example of its use below:

List<int> values = new List<int>() { 7, 14, 28, 35, 77, 34, 52, 16,
777, 115};

IEnumerable<IGrouping<int, int>> query = from value in values
											   group value by value % 2;

foreach (var group in query)
{
	Console.WriteLine(group.Key == 0 ? "\nEven values:" : "\nOdd values:");
	foreach (int i in group)
		Console.WriteLine(i);
}

The ToLookup method creates a Lookup<TKey, TElement> from an IEnumberable<T> based on a key selector function. Its syntax follows:

public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
	this IEnumerable<TSource> source,
	Func<TSource, TKey> keySelector
)

This method allows for the grouping of items through a key. The key also serves the purpose of gaining access to the items efficiently rather than through iteration like GroupBy. Review an example below:

static void Main(string[] args)
	{
		List<string> surnames = new List<string>();
		surnames.Add("Starr");
		surnames.Add("Crabtree");
		surnames.Add("Nevermind");

		ILookup<char, string> surnamesByInitial = surnames.ToLookup((n) => n[0]);

		Console.WriteLine("T's: {0}", surnamesByInitial['T'].Count());
		Console.WriteLine("S's: {0}", surnamesByInitial['S'].Count());
		Console.WriteLine("P's: {0}", surnamesByInitial['P'].Count());
	}