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

GroupBy operation in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
GroupBy operation
📖 Scenario: You work in a small store. You have a list of sales records. Each record has a Product name and a Quantity sold.You want to group these sales by product to see how many units of each product were sold in total.
🎯 Goal: Build a program that groups sales by product name and sums the quantities for each product.
📋 What You'll Learn
Create a list of sales records with exact products and quantities
Create a variable to hold the grouped sales result
Use LINQ GroupBy to group sales by product
Sum the quantities for each product group
Print the product name and total quantity sold for each group
💡 Why This Matters
🌍 Real World
Grouping sales data by product helps stores understand which products sell the most and manage inventory better.
💼 Career
Data grouping and aggregation are common tasks in software development, especially in reporting, analytics, and business intelligence roles.
Progress0 / 4 steps
1
Create the sales data list
Create a list called sales of Sale objects with these exact entries: new Sale("Apple", 10), new Sale("Banana", 5), new Sale("Apple", 7), new Sale("Orange", 3), new Sale("Banana", 2). Also define the Sale class with public properties Product (string) and Quantity (int).
C Sharp (C#)
Need a hint?

Define the Sale class first. Then create a List<Sale> called sales with the exact entries.

2
Create a variable for grouped sales
Add a variable called groupedSales of type var to hold the grouped sales result. Initialize it to null for now.
C Sharp (C#)
Need a hint?

Use sales.GroupBy(sale => sale.Product) to group sales by product.

3
Sum quantities for each product group
Change the groupedSales variable to hold the result of grouping sales by Product and summing the Quantity for each group. Use LINQ GroupBy and Select to create an anonymous type with Product and TotalQuantity.
C Sharp (C#)
Need a hint?

Use Select after GroupBy to create a new object with Product and the sum of Quantity.

4
Print the grouped sales totals
Use a foreach loop to print each product and its total quantity from groupedSales. Use Console.WriteLine with the format: "Product: {product}, Total Quantity: {total}".
C Sharp (C#)
Need a hint?

Use a foreach loop to print each group's product and total quantity using Console.WriteLine and string interpolation.