GroupBy
This method transforms a collection into groups. Each group has a key. With this method from the System.Linq
namespace, you can apply grouping to many collections.
The GroupBy
method can be used in away similar to a Dictionary
of Lists. As with other LINQ methods, GroupBy
has possible performance drawbacks.
We call GroupBy
with the argument being a lambda expression. Each element is identified as "a" in the lambda expression in the example program.
IsEven
, which is a boolean value. Thus the result is two groups with the keys True and False.using System; using System.Linq; class Program { static void Main() { // Input array. int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Group elements by IsEven. var result = array.GroupBy(a => IsEven(a)); // Loop over groups. foreach (var group in result) { // Display key for group. Console.WriteLine("IsEven = {0}:", group.Key); // Display values in group. foreach (var value in group) { Console.Write("{0} ", value); } // End line. Console.WriteLine(); } } static bool IsEven(int value) { return value % 2 == 0; } }IsEven = False: 1 3 5 7 9 IsEven = True: 2 4 6 8
Using GroupBy()
is fine for certain parts of programs. However, if you are generating a collection that will be repeatedly used, it would be better to use ToDictionary
.
GroupBy
can index elements by keys, a Dictionary
can do this and has the performance advantages provided by hashing.Collection
notesIf each group contains multiple elements as is typical with GroupBy
, you could use a List
as the value of the Dictionary
instance. Thus you would have a Dictionary
of Lists.
We looked at the GroupBy
extension method in the C# programming language. This is effective in dividing up a collection of elements.