Group by Operator in C#

The Group By operator in C# is used to group elements in a collection based on a specified key. It separates the results into groups where each group contains elements that share the same key value.

Syntax

Following is the syntax for using Group By with LINQ query syntax −

var result = from element in collection
             group element by keySelector;

Following is the syntax for using Group By with method syntax −

var result = collection.GroupBy(keySelector);

Parameters

  • element − The individual item in the collection being grouped.

  • keySelector − A function that extracts the key for each element to determine grouping.

Return Value

The Group By operator returns an IEnumerable<IGrouping<TKey, TSource>> where each group has a Key property and contains elements that match that key.

Group By Operation Original Array [5, 10, 15, 20, 25, 30] Group by: element >= 20 Group: False [5, 10, 15] Group: True [20, 25, 30] Elements grouped by condition result

Using Group By with Boolean Condition

The following example groups numbers based on whether they are greater than or equal to 20 −

using System;
using System.Linq;

class Demo {
    static void Main() {
        int[] a = { 5, 10, 15, 20, 25, 30 };
        var check = from element in a 
                    orderby element 
                    group element by chkGreater(element);
                    
        foreach (var val in check) {
            Console.WriteLine("Group Key: " + val.Key);
            foreach (var res in val) {
                Console.WriteLine("  " + res);
            }
        }
    }
    
    static bool chkGreater(int a) {
        return a >= 20;
    }
}

The output of the above code is −

Group Key: False
  5
  10
  15
Group Key: True
  20
  25
  30

Using Group By with Method Syntax

The same operation can be performed using method syntax −

using System;
using System.Linq;

class Demo {
    static void Main() {
        string[] names = { "Alice", "Bob", "Charlie", "David", "Eva" };
        
        var groupedByLength = names.GroupBy(name => name.Length);
        
        foreach (var group in groupedByLength) {
            Console.WriteLine($"Names with {group.Key} characters:");
            foreach (var name in group) {
                Console.WriteLine("  " + name);
            }
        }
    }
}

The output of the above code is −

Names with 5 characters:
  Alice
  David
Names with 3 characters:
  Bob
  Eva
Names with 7 characters:
  Charlie

Group By with Complex Objects

Group By can also work with complex objects. Here's an example grouping students by their grade −

using System;
using System.Linq;
using System.Collections.Generic;

class Student {
    public string Name { get; set; }
    public char Grade { get; set; }
    
    public Student(string name, char grade) {
        Name = name;
        Grade = grade;
    }
}

class Program {
    static void Main() {
        List<Student> students = new List<Student> {
            new Student("John", 'A'),
            new Student("Mary", 'B'),
            new Student("Tom", 'A'),
            new Student("Lisa", 'C'),
            new Student("Sam", 'B')
        };
        
        var groupedByGrade = from student in students
                           group student by student.Grade;
                           
        foreach (var group in groupedByGrade) {
            Console.WriteLine($"Grade {group.Key}:");
            foreach (var student in group) {
                Console.WriteLine("  " + student.Name);
            }
        }
    }
}

The output of the above code is −

Grade A:
  John
  Tom
Grade B:
  Mary
  Sam
Grade C:
  Lisa

Conclusion

The Group By operator in C# is a powerful LINQ feature that organizes collections into groups based on a specified key. It returns groups with a Key property and elements that match that key, making it ideal for data categorization and analysis operations.

Updated on: 2026-03-17T07:04:35+05:30

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements