C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: The key becomes the result of IsEven, which is a boolean value. Thus the result is two groups with the keys True and False.
Results: The group with the key of value False contains the odds. And the group with the key of value True, meanwhile, contains the evens.
C# program that uses GroupBy method
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;
}
}
Output
IsEven = False:
1 3 5 7 9
IsEven = True:
2 4 6 8
And: While GroupBy can index elements by keys, a Dictionary can do this and has the performance advantages provided by hashing.
Group ByToDictionary