0
0
C Sharp (C#)programming~5 mins

GroupBy operation in C Sharp (C#)

Choose your learning style9 modes available
Introduction

GroupBy helps you organize items into groups based on a shared property. It makes it easy to see which items belong together.

When you want to count how many items share the same category.
When you want to list items grouped by a common feature, like all students by their grade.
When you want to summarize data by groups, like total sales per product.
When you want to separate a list into smaller lists based on a key.
Syntax
C Sharp (C#)
var grouped = collection.GroupBy(item => item.KeyProperty);

GroupBy returns groups as IGrouping<TKey, TElement> collections.

You access each group's key with group.Key and its items by iterating over the group.

Examples
Groups numbers into "Even" and "Odd" groups.
C Sharp (C#)
var numbers = new List<int> {1, 2, 3, 4, 5, 6};
var grouped = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd");
Groups words by their first letter.
C Sharp (C#)
var words = new List<string> {"apple", "banana", "apricot", "blueberry"};
var grouped = words.GroupBy(w => w[0]);
Sample Program

This program groups a list of fruits by their first letter and prints each group with its fruits.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var fruits = new List<string> { "apple", "banana", "apricot", "blueberry", "avocado" };
        var groupedFruits = fruits.GroupBy(f => f[0]);

        foreach (var group in groupedFruits)
        {
            Console.WriteLine($"Fruits starting with '{group.Key}':");
            foreach (var fruit in group)
            {
                Console.WriteLine($" - {fruit}");
            }
        }
    }
}
OutputSuccess
Important Notes

Groups are lazy-evaluated, so the grouping happens when you iterate over them.

You can use GroupBy with any property or computed key.

Summary

GroupBy organizes items into groups by a key.

You get a collection of groups, each with a key and items.

It helps summarize or categorize data easily.